package com.yanqu.road.server.manger.activity.unionwar;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.unionwar.*;
import com.yanqu.road.entity.activity.unionwar.enums.eTimeInfoPeriodType;
import com.yanqu.road.entity.activity.unionwar.result.CurrentTimeInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.cricket.CricketData;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.LogUnionWarActivityDispatch;
import com.yanqu.road.entity.log.LogUnionWarActivityGoodsUse;
import com.yanqu.road.entity.manor.FishData;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.entity.unionwar.BaseUnionGuessInfo;
import com.yanqu.road.entity.unionwar.ConditionAchieveInfo;
import com.yanqu.road.entity.unionwar.GuessUnionInfo;
import com.yanqu.road.entity.unionwar.UserUnionWarGuessData;
import com.yanqu.road.logic.bussiness.activity.UnionWarActivityBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.CrossRankPb;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.logic.pb.UnionWarActivityPb;
import com.yanqu.road.pb.activity.unionwar.CrossUnionWarProto;
import com.yanqu.road.pb.activity.unionwar.UnionWarActivityServerProto;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.pb.rank.UnionActivityRankProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.unionwar.UnionWarActivityModule;
import com.yanqu.road.server.gameplayer.module.cricket.CricketMgr;
import com.yanqu.road.server.gameplayer.module.cricket.CricketModule;
import com.yanqu.road.server.gameplayer.module.manor.ManorModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.vehicle.VehicleModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.cross.CrossDataMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.manor.FishPondMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class UnionWar {

    private static Logger logger = LogManager.getLogger(UnionWar.class.getName());

    private ActivityInfo activityInfo;

    //type session   阶段类型  场次
    private Map<Integer, Map<Integer, UnionQunyingTimeInfo>> timeInfoConfigMap;

    //conditionType
    private Map<Integer, List<ActivityConditionInfo>> activityConditionInfoMap;

    //mallId
    private Map<Integer, MallInfo> activityMallInfoMap;

    //赛制配置
    private List<UnionQunyingTimeInfo> timeInfoList;

    //unionUid phase session
    private Map<String, Map<Integer, Map<Integer, UnionWarDispatchDetail>>> unionDispatchDetailMap = new ConcurrentHashMap<>();

    //unionUid phase session
    private Map<String, Map<Integer, Map<Integer, UnionWarUnionMember>>>  unionMemberMap;        //每场次商会成员

    //phase - serverId - UnionUid
    private Map<Integer, Map<Long, Map<String , GuessUnionInfo>>> guessUnionInfoMap;  //竞猜商会数据

    //groupId conditionId
    private Map<Integer, Map<Integer, ConditionAchieveInfo>> conditionAchieveInfoMap;  //竞猜奖励各个档位达成人数

    //unionUid phase
    private Map<String, Map<Integer, Map<Long, UnionWarRankMember>>> canGetRankRewardMemberMap;    //排行榜可领奖商会成员

    //phase session     战斗明细
    private Map<Integer, Map<Integer, Map<Integer, Map<String, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg>>>> battleResultMap;

    //phase session no   精彩对阵
    private Map<Integer, Map<Integer, Map<String, UnionWarActivityServerProto.MatchVideoBattleTemp>>> matchVideoBattleMap;

    private Map<Long, Map<Integer, UserPatronsSendTimes>> userPatronsSendMap;

    private Map<Long, Map<String, UserVehicleSendTimes>> userVehicleSendMap;

    private Map<Long, Map<Integer, UserFishSendTimes>> userFishSendMap;

    private Map<Long, Map<Integer, UserCricketSendTimes>> userCricketSendMap;

    //活动参赛商会
    private Map<Integer, List<UnionWarUnionJoin>> unionWarNameListMap;

    private Map<String, Object> unionLocker;

    private Map<Long, Object> userLocker;
    //积分赛参数人数（区服排名前n)
    public int SCORE_PHASE_UNION_N;
    //决赛参数人员(积分赛排名前n)
    public int FINALS_PHASE_UNION_N;

    private boolean requestCrossDetail;

    /**
     * 门客、珍兽、锦囊使用次数
     */
    public static int DISPATCH_TIMES = 1;

    public UnionWar(ActivityInfo activityInfo, Map<Integer, MallInfo> mallInfoMap, Map<Integer, List<ActivityConditionInfo>> conditionListMap) {
        this.activityInfo = activityInfo;
        this.activityMallInfoMap = mallInfoMap;
        this.activityConditionInfoMap = conditionListMap;
        unionLocker = new ConcurrentHashMap<>();
        userLocker = new ConcurrentHashMap<>();
        canGetRankRewardMemberMap = new ConcurrentHashMap<>();
        conditionAchieveInfoMap = new ConcurrentHashMap<>();
        guessUnionInfoMap = new ConcurrentHashMap<>();
        requestCrossDetail = false;
        initActivityConfig();
    }

    public void syncConditionAchieveInfoMap() {
        //积分赛阶段完才需要去同步
        UnionQunyingTimeInfo timeInfo = getCurrentTimeInfo().getTimeInfo();
        if ((timeInfo != null && timeInfo.getType() == 2) || getCurrentTimeInfo().getPeriodType() == eTimeInfoPeriodType.ReceiveTime) {
            List<Integer> groupIdList = getGroupListByServerId(activityInfo.getActivityId(), GameServer.getInstance().getServerId());
            for (Integer groupId : groupIdList) {
                UnionWarActivityServerProto.UnionWarConditionAchieveReqMsg.Builder reqMsg = UnionWarActivityServerProto.UnionWarConditionAchieveReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                reqMsg.setGroupId(groupId);
                //GamePlayerMgr.sendChannelPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_WAR_SYNC_CONDITION_ACHIEVE, reqMsg));
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_UNION_WAR_SYNC_CONDITION_ACHIEVE, reqMsg, 0, activityInfo.getActivityId(), groupId);
            }
        }
    }


    public void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        playerList.forEach(player ->{
            UnionWarActivityModule activityModule = player.getModule(UnionWarActivityModule.class);
            activityModule.addNewActivity(activityInfo);
            activityModule.syncData(activityInfo);
        });
    }


    public List<ActivityConditionInfo> getActivityConditionInfoList(int type) {
        return activityConditionInfoMap.get(type);
    }

    public Map<Integer, List<ActivityConditionInfo>> getActivityConditionInfoMap() {
        return activityConditionInfoMap;
    }

    public Map<String, Map<Integer, Map<Integer, UnionWarUnionMember>>> getUnionMemberMap() {
        return unionMemberMap;
    }

    public Map<Integer, Map<Integer, Map<Integer, Map<String, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg>>>> getBattleResultMap() {
        return battleResultMap;
    }

    public Map<Long, Map<Integer, UserPatronsSendTimes>> getUserPatronsSendMap() {
        return userPatronsSendMap;
    }

    public Map<Long, Map<String, UserVehicleSendTimes>> getUserVehicleSendMap() {
        return userVehicleSendMap;
    }

    public Map<Long, Map<Integer, UserFishSendTimes>> getUserFishSendMap() {
        return userFishSendMap;
    }

    public Map<Long, Map<Integer, UserCricketSendTimes>> getUserCricketSendMap() {
        return userCricketSendMap;
    }

    public Map<Integer, Map<Integer, Map<String, UnionWarActivityServerProto.MatchVideoBattleTemp>>> getMatchVideoBattleMap() {
        return matchVideoBattleMap;
    }

    public List<UnionQunyingTimeInfo> getTimeInfoList() {
        return timeInfoList;
    }

    public Map<Integer, List<UnionWarUnionJoin>> getUnionWarNameList() {
        return unionWarNameListMap;
    }

    public Map<String, Map<Integer, Map<Long, UnionWarRankMember>>> getCanGetRankRewardMemberMap() {
        return canGetRankRewardMemberMap;
    }

    public ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public void setActivityInfo(ActivityInfo activityInfo, Map<Integer, MallInfo> mallInfoMap,  Map<Integer, List<ActivityConditionInfo>> activityConditionInfoMap) {
        this.activityInfo = activityInfo;
        this.activityMallInfoMap = mallInfoMap;
        this.activityConditionInfoMap = activityConditionInfoMap;
        initActivityConfig();
        playerReloadActivity();
    }

    /**
     * 初始活动配置
     */
    private void initActivityConfig() {
        logger.info("init union war activity {} config", activityInfo.getActivityId());
        List<UnionQunyingTimeInfo> tempTimeInfoList = UnionWarActivityBusiness.getUnionQunyingTimeInfo(activityInfo.getActivityId());
        Map<Integer, Map<Integer, UnionQunyingTimeInfo>> tempTimeInfoConfigMap = new ConcurrentHashMap<>();
        for (UnionQunyingTimeInfo timeInfo : tempTimeInfoList) {
            if (!tempTimeInfoConfigMap.containsKey(timeInfo.getType())) {
                tempTimeInfoConfigMap.put(timeInfo.getType(), new ConcurrentHashMap<>());
            }
            tempTimeInfoConfigMap.get(timeInfo.getType()).put(timeInfo.getSession(), timeInfo);
        }
        timeInfoConfigMap = tempTimeInfoConfigMap;
        timeInfoList = tempTimeInfoList;
        //解析扩展参数
        UnionQunyingTimeInfo qunyingTimeInfo = getUnionQunyingTimeInfo(1, 0);
        if(qunyingTimeInfo != null){
            SCORE_PHASE_UNION_N = Integer.valueOf(qunyingTimeInfo.getParam());
            CrossUnionServerGroup serverGroup = CrossUnionServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
            if (serverGroup != null && serverGroup.getServerList().size() > 0) {
                SCORE_PHASE_UNION_N = SCORE_PHASE_UNION_N * serverGroup.getServerList().size();
            }
        }
        qunyingTimeInfo = getUnionQunyingTimeInfo(2, 0);
        if(qunyingTimeInfo != null){
            FINALS_PHASE_UNION_N = Integer.valueOf(qunyingTimeInfo.getParam());
        }
        //校验
        int m = getAllSession(2);
        if(1 << m < FINALS_PHASE_UNION_N){
            logger.error("activityId {} TimeInfo config error, m {}, n {}", activityInfo.getActivityId(), m, FINALS_PHASE_UNION_N);
        }
    }

    public UnionQunyingTimeInfo getUnionQunyingTimeInfo(int phase, int session){
        Map<Integer, UnionQunyingTimeInfo> sessionMap = timeInfoConfigMap.get(phase);
        if(sessionMap == null){
            return null;
        }
        return sessionMap.get(session);
    }

    /**
     * 加载活动数据
     */
    public void loadActivityData() {
        unionDispatchDetailMap = UnionWarActivityBusiness.getUnionDispatchDetailMap(activityInfo.getActivityId());
        unionWarNameListMap = UnionWarActivityBusiness.getUnionWarNameList(activityInfo.getActivityId());
        unionMemberMap = UnionWarActivityBusiness.getUnionMemberMap(activityInfo.getActivityId());
        canGetRankRewardMemberMap = UnionWarActivityBusiness.getUnionWarRankMemberMap(activityInfo.getActivityId());
        userPatronsSendMap = UnionWarActivityBusiness.getUserPatronsSendTimes(activityInfo.getActivityId());
        userVehicleSendMap = UnionWarActivityBusiness.getUserVehicleSendTimes(activityInfo.getActivityId());
        userFishSendMap = UnionWarActivityBusiness.getUserFishSendTimes(activityInfo.getActivityId());
        userCricketSendMap = UnionWarActivityBusiness.getUserCricketSendTimes(activityInfo.getActivityId());
        battleResultMap = new ConcurrentHashMap<>();
        matchVideoBattleMap = new ConcurrentHashMap<>();
    }

    /**
     * 卸载活动数据
     */
    public void removeActivityData() {
        logger.info("remove union war activity {} activityData", activityInfo.getActivityId());

    }

    /**
     * 获取当前活动周期
     * @return
     */
    public CurrentTimeInfo getCurrentTimeInfo(){
        CurrentTimeInfo currentTimeInfo = new CurrentTimeInfo();
        int currentSecond = DateHelper.getCurrentSecond();
        if(currentSecond >= activityInfo.getBeginShowTime() && currentSecond <= activityInfo.getBeginTime()){
            currentTimeInfo.setPeriodType(eTimeInfoPeriodType.ShowTime);
            return currentTimeInfo;
        }
        //不在活动期间，没有任何阶段、周期
        if(currentSecond >= activityInfo.getEndShowTime() || currentSecond < activityInfo.getBeginShowTime()){
            return currentTimeInfo;
        }
        //活动领奖期
        if(currentSecond >= activityInfo.getEndTime() && currentSecond < activityInfo.getEndShowTime()){
            currentTimeInfo.setPeriodType(eTimeInfoPeriodType.ReceiveTime);
            return currentTimeInfo;
        }
        UnionQunyingTimeInfo current = null;
        long gapSecond = System.currentTimeMillis() / 1000 - activityInfo.getBeginTime();
        for(int i = 0; i < timeInfoList.size(); i++){
            UnionQunyingTimeInfo timeInfo = timeInfoList.get(i);
            //beginTime至第一周期之前
            if(timeInfo.getType() == 1 && timeInfo.getSession() == 0 && gapSecond < timeInfo.getBeginTime() * 60){
                currentTimeInfo.setPeriodType(eTimeInfoPeriodType.ShowTime);
                return currentTimeInfo;
            }
            if(gapSecond >= timeInfo.getBeginTime() * 60 && gapSecond <= (timeInfo.getBeginTime() + timeInfo.getDurTime()) * 60){
                current = timeInfo;
                if(current.getSession() == 0){
                    currentTimeInfo.setPeriodType(eTimeInfoPeriodType.PrepareTime);
                }else {
                    currentTimeInfo.setPeriodType(eTimeInfoPeriodType.FightingTime);
                }
            }else {
                //战斗周期的间隔视为下一战斗周期的备战期
                if(i < timeInfoList.size() -1){
                    UnionQunyingTimeInfo nextTimeInfo = timeInfoList.get(i + 1);
                    if(gapSecond > (timeInfo.getBeginTime() + timeInfo.getDurTime()) * 60 && gapSecond < nextTimeInfo.getBeginTime() * 60){
                        current = nextTimeInfo;
                        currentTimeInfo.setPeriodType(eTimeInfoPeriodType.PrepareTime);
                    }
                }
            }
            if(current != null){
                break;
            }
        }
        //配置错误,活动结束时间应等于最后一个周期的结束时间(beginTime + durTime)
        if(current == null && currentSecond < activityInfo.getEndTime() && currentSecond > activityInfo.getBeginTime()){
            //logger.error("activity {} endTime not config equals last timeId endTime", activityInfo.getActivityId());
            currentTimeInfo.setPeriodType(eTimeInfoPeriodType.ReceiveTime);
        }
        currentTimeInfo.setTimeInfo(current);
        return currentTimeInfo;
    }

    /**
     * 获取参赛商会
     * @param unionUid
     * @return
     */
    public UnionWarUnionJoin getUnionWarNameList(String unionUid){
        UnionWarUnionJoin unionName = null;
        for (Map.Entry<Integer, List<UnionWarUnionJoin>> entry : unionWarNameListMap.entrySet()) {
            for (int i = 0; i < entry.getValue().size(); i++) {
                UnionWarUnionJoin nameList = entry.getValue().get(i);
                if (unionUid.equals(nameList.getUnionUid())) {
                    unionName = nameList;
                    break;
                }
            }
        }
        return unionName;
    }

    /**
     * 是否有当前周期参赛资格
     * @param unionUid
     * @param timeInfo
     * @return
     */
    public boolean isJoinCurrentTimeInfo(String unionUid, UnionQunyingTimeInfo timeInfo){
        if(timeInfo == null){
            timeInfo = getCurrentTimeInfo().getTimeInfo();
        }
        if(timeInfo == null){
            return false;
        }
        boolean join = isJoin(unionUid);
        if(!join){
            return false;
        }
        if(timeInfo.getType() == 1){
            UnionQunyingTimeInfo now = getCurrentTimeInfo().getTimeInfo();
            if(now.getType() == 1 && timeInfo.getSession() < now.getSession()){
                return false;
            }
        }
        if(2 == timeInfo.getType() && timeInfo.getSession() < 2){  //决赛看是否有备战数据(或者积分赛排名前N)
            UnionWarUnionJoin unionName = getUnionWarNameList(unionUid);
            if(unionName.getPhaseOneRank() <= FINALS_PHASE_UNION_N && unionName.getPhaseOneRank() > 0){
                return true;
            }
            UnionWarDispatchDetail detail = getUnionWarDispatchDetailList(unionUid, 2, timeInfo.getSession());
            if(detail == null){
                join = false;
            }else {
                join = true;
            }
        }else if(2 == timeInfo.getType() && timeInfo.getSession() <= getAllSession(2)){ //决赛第二、三轮资格，看上一轮胜负
            //v2.6
            UnionQunyingTimeInfo now = getCurrentTimeInfo().getTimeInfo();
            //前名轮次
            if(now != null && now.getType() == 2 && timeInfo.getSession() < now.getSession()){
                return false;
            }
            //有败绩即为淘汰，无后续场次资格
            for(int s = 1; s <= timeInfo.getSession(); s++){
                UnionWarDispatchDetail detail = getUnionWarDispatchDetailList(unionUid, 2, s);
                if(null == detail){
                    return false;
                }
                if(detail.getWinMark() == eUnionWarWinMark.Lose.getValue()){
                    return false;
                }
            }
        }
        return join;
    }

    /**
     * 商会是否参与活动
     * @param unionUid
     * @return
     */
    public boolean isJoin(String unionUid) {
        if(null == getUnionWarNameList(unionUid)){
            return false;
        }
        return true;
    }

    /**
     * 获取总战斗场次
     * @param phase 当前阶段
     * @return
     */
    public int getAllSession(int phase){
        Map<Integer, UnionQunyingTimeInfo> timeInfoMap = timeInfoConfigMap.get(phase);
        if(timeInfoMap == null){
            return 0;
        }
        //扣除session=0
        return timeInfoMap.size() - 1;
    }

    public UnionWarDispatchDetail getUnionWarDispatchDetailList(String unionUid, int phase, int session) {
        Map<Integer, UnionWarDispatchDetail> sessionMap = getUnionWarDispatchDetailList(unionUid, phase);
        if(sessionMap == null){
            return null;
        }
        return sessionMap.get(session);
    }

    public Map<Integer, UnionWarDispatchDetail> getUnionWarDispatchDetailList(String unionUid, int phase) {
        Map<Integer, Map<Integer, UnionWarDispatchDetail>> map = unionDispatchDetailMap.get(unionUid);
        if (map == null) {
            return null;
        }
        return map.get(phase);
    }

    public Map<Integer, Map<Integer, UnionWarDispatchDetail>> getUnionWarDispatchDetailList(String unionUid) {
        return unionDispatchDetailMap.get(unionUid);
    }

    public Map<String, Map<Integer, Map<Integer, UnionWarDispatchDetail>>> getUnionWarDispatchDetailList() {
        return unionDispatchDetailMap;
    }

    /**
     * 获取场次战斗结果（明细）
     * @param phase
     * @param session
     * @return
     */
    public Map<String, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg> getCrossUnionWarBattleResult(int phase, int session, int groupId){
        Map<Integer, Map<Integer, Map<String, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg>>> phaseMap = battleResultMap.get(phase);
        if(phaseMap == null){
            return null;
        }
        Map<Integer, Map<String, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg>> sessionMap = battleResultMap.get(phase).get(session);
        if(sessionMap == null){
            return null;
        }
        return sessionMap.get(groupId);
    }

    /**
     * 获取商会场次战斗结果（明细）
     * @param unionUid
     * @param phase
     * @param session
     * @return
     */
    public CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg getCrossUnionWarBattleResult(String unionUid, int phase, int session, int groupId){
        Map<String, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg> unionMap = getCrossUnionWarBattleResult(phase, session, groupId);
        if(unionMap == null){
            return null;
        }
        return unionMap.get(unionUid);
    }

    /**
     * 获取场次精彩对阵
     * @param phase
     * @param session
     * @return
     */
    public List<UnionWarActivityServerProto.MatchVideoBattleTemp> getMatchVideoBattleTempList(int phase, int session, int groupId){
        Map<Integer, Map<String, UnionWarActivityServerProto.MatchVideoBattleTemp>> sessionMap = matchVideoBattleMap.get(phase);
        if(sessionMap == null){
            return new ArrayList<>();
        }
        Map<String, UnionWarActivityServerProto.MatchVideoBattleTemp> battleMap = sessionMap.get(session);
        if(battleMap == null){
            return new ArrayList<>();
        }
        List<UnionWarActivityServerProto.MatchVideoBattleTemp> resultList = new ArrayList<>(battleMap.values());
        if(groupId > 0){
            UnionActivityGroup activityGroup = GameUnionActivityGroupMgr.getGroupData(this.getActivityInfo().getActivityId(), groupId);
            if(activityGroup != null){
                List<String> unionList = new ArrayList<>(activityGroup.getUnionDataMap().keySet());
                if(unionList.size() > 0){
                    resultList.removeIf(temp -> !unionList.contains(temp.getUnionUid()) && !unionList.contains(temp.getEnemyUnionUid()));
                }
            }
        }
        return resultList;
    }

    public UserPatronsSendTimes getUserPatronsSend(long userId, int patronsId){
        Map<Integer, UserPatronsSendTimes> patronsSendTimesMap = getUserPatronsSendMap().get(userId);
        if(patronsSendTimesMap == null){
            return null;
        }
        return patronsSendTimesMap.get(patronsId);
    }

    public UserVehicleSendTimes getUserVehicleSend(long userId, String vehicleId){
        Map<String, UserVehicleSendTimes> vehicleSendTimesMap = getUserVehicleSendMap().get(userId);
        if(vehicleSendTimesMap == null){
            return null;
        }
        return vehicleSendTimesMap.get(vehicleId);
    }

    public UserFishSendTimes getUserFishSend(long userId, int fishId){
        Map<Integer, UserFishSendTimes> fishSendTimesMap = userFishSendMap.get(userId);
        if(fishSendTimesMap == null){
            return null;
        }
        return fishSendTimesMap.get(fishId);
    }

    public UserCricketSendTimes getUserCricketSend(long userId, int cricketId){
        Map<Integer, UserCricketSendTimes> fishSendTimesMap = userCricketSendMap.get(userId);
        if(fishSendTimesMap == null){
            return null;
        }
        return fishSendTimesMap.get(cricketId);
    }

    /**
     * 检测是否在特定阶段场次的备战周期
     * @param phase
     * @param session
     * @return
     */
    private int checkTimeInfoInPrepareTime(int phase, int session){
        //周期检测
        CurrentTimeInfo currentTimeInfo = getCurrentTimeInfo();
        if(currentTimeInfo.getTimeInfo() == null){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_OVER_PREPARE_TIME;
        }
        if(phase != currentTimeInfo.getTimeInfo().getType() || session < currentTimeInfo.getTimeInfo().getSession()){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_OVER_PREPARE_TIME;
        }
        if(currentTimeInfo.getPeriodType() == eTimeInfoPeriodType.FightingTime && session == currentTimeInfo.getTimeInfo().getSession()){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_OVER_PREPARE_TIME;
        }
        return 0;
    }

    /**
     * 是否处于竞猜时间
     *
     * @param phase 阶段
     * @return
     */
    public boolean checkInGuessTime(int phase) {
        CurrentTimeInfo currentTimeInfo = getCurrentTimeInfo();
        if (currentTimeInfo.getTimeInfo() == null) {
            return false;
        }
        if(currentTimeInfo.getTimeInfo().getType() != phase){
            return false;
        }
        if(phase == 1 && currentTimeInfo.getTimeInfo().getType() == phase){
            return currentTimeInfo.getTimeInfo().getSession() == 0;
        }
        if(phase == 2 && currentTimeInfo.getTimeInfo().getType() == phase){
            int session = currentTimeInfo.getTimeInfo().getSession();
            return session == 0;
        }
        return false;
    }

    /**
     * 是否处于领奖时间
     *
     * @param phase 阶段
     * @return
     */
    public boolean checkInGetRewardTime(int phase) {
        CurrentTimeInfo currentTimeInfo = getCurrentTimeInfo();
        if(currentTimeInfo.getPeriodType() == eTimeInfoPeriodType.ReceiveTime){
            return true;
        }
        if (currentTimeInfo.getTimeInfo() == null) {
            return false;
        }
        if (phase == 1) {
            return currentTimeInfo.getTimeInfo().getType() == 2;
        } else if (phase == 2) {
            return DateHelper.getCurrentSecond() > activityInfo.getEndTime() + 5 * DateHelper.MINUTE_SECONDS;
        }
        return false;
    }

    /**
     * 初始派遣明细
     * @param unionUid
     * @param phase
     * @param session
     * @param detail
     */
    private void initDispatchDetail(String unionUid, int phase, int session, UnionWarDispatchDetail detail) {
        detail.setInsertOption();
        detail.setActivityId(activityInfo.getActivityId());
        detail.setSession(session);
        detail.setPhase(phase);
        detail.setUnionUid(unionUid);
    }

    public void initCrossUnionWarUnionLockListFromCross(List<CrossUnionProto.CrossUnionActivityLockRankTemp> tempList, int groupId){
        synchronized (this) {
            List<UnionWarUnionJoin> unionWarNameList = unionWarNameListMap.get(groupId);
            if (unionWarNameList == null || unionWarNameList.size() == 0) {
                if (unionWarNameList == null) {
                    unionWarNameList = new ArrayList<>();
                    unionWarNameListMap.put(activityInfo.getActivityId(), unionWarNameList);
                }
                for (int i = 0; i < tempList.size(); i++) {
                    CrossUnionProto.CrossUnionActivityLockRankTemp rankTemp = tempList.get(i);
                    UnionWarUnionJoin name = new UnionWarUnionJoin();
                    name.setRankNum(i);
                    name.setActivityId(activityInfo.getActivityId());
                    name.setUnionUid(rankTemp.getUnionUid());
                    name.setGroupId(groupId);
                    UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(rankTemp.getUnionUid());
                    if (unionBaseInfo != null) {
                        name.setUnionBaseInfo(unionBaseInfo);
                    }
                    name.setInsertOption();
                    name.setGroupId(groupId);
                    unionWarNameList.add(name);
                }
                logger.info("union war activity {}, groupId {} union list size {}", activityInfo.getActivityId(), groupId, unionWarNameList.size());
                //初始化积分赛所有场次的备战基础数据
                CrossUnionServerGroup group = CrossUnionServerGroupMgr.getServerGroupByServerId(ConfigHelper.getLong("serverId"));
                Set<Long> serverSet = new HashSet<>();
                serverSet.add(ConfigHelper.getLong("serverId"));
                if (group != null) {
                    serverSet.addAll(group.getServerList());
                }
                for (UnionWarUnionJoin nameList : unionWarNameList) {
                    //只初始本分组的备战
                    if(nameList.getUnionBaseInfo() != null) {
                        if (!serverSet.contains(nameList.getUnionBaseInfo().getServerId())) {
                            continue;
                        }
                    }
                    Object lock = getUnionLocker(nameList.getUnionUid());
                    synchronized (lock) {
                        for (int session = 1; session <= getAllSession(1); session++) {
                            UnionWarDispatchDetail detail = checkAndGetUnionWarDispatchDetails(nameList.getUnionUid(), 1, session);
                            detail.setGroupId(groupId);
                            if(detail.getUnionInfo() == null){
                                detail.setUnionInfo(nameList.getUnionBaseInfo());
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 确定参战资格名单及推送跨服
     */
    public void initCrossUnionWarUnion() {
        if (null != activityInfo) {
            List<Integer> groupIdList = getGroupListByServerId(activityInfo.getActivityId(), GameServer.getInstance().getServerId());
            for (int groupId : groupIdList) {
                initCrossUnionWarUnion(groupId);
            }
        }
    }

    private void initCrossUnionWarUnion(int groupId) {
        if(!CrossUnionMgr.isAllSync()){
            return;
        }
        long nowTime = System.currentTimeMillis() / 1000;
        if (nowTime >= activityInfo.getBeginShowTime() && nowTime < activityInfo.getEndTime()) {
            List<UnionWarUnionJoin> unionWarNameList = unionWarNameListMap.get(groupId);
            UnionActivityGroup activityGroup = GameUnionActivityGroupMgr.getGroupData(activityInfo.getActivityId(), groupId);
            if(activityGroup == null){
                return;
            }
            int needNum;
            //是否是旧逻辑
            List<Integer> paramList = StringUtils.stringToIntegerList(activityInfo.getUnionGroup(), "\\|");
            needNum = paramList.get(1);
            if(activityGroup.getUnionDataMap().size() < needNum){
                return;
            }
            if (unionWarNameList == null || unionWarNameList.size() == 0) {
                if (unionWarNameList == null) {
                    unionWarNameList = new ArrayList<>();
                    unionWarNameListMap.put(groupId, unionWarNameList);
                }
                //排序
                List<UnionActivityGroupUnion> poolList = new ArrayList<>(activityGroup.getUnionDataMap().values());
                poolList.sort((o1, o2) -> o2.getUnionBaseInfo().getTotalEarnSpeed().compareTo(o1.getUnionBaseInfo().getTotalEarnSpeed()));

                    for (int i = 0; i < poolList.size(); i++) {
                        UnionActivityGroupUnion groupUnion  = poolList.get(i);
                        if(groupUnion.getLocked() == 0){
                            continue;
                        }
                        UnionBaseInfo unionBaseInfo = groupUnion.getUnionBaseInfo();
                        if(unionBaseInfo == null){
                            unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(groupUnion.getUnionUid());
                        }
                        UnionWarUnionJoin old = null;
                        for (UnionWarUnionJoin unionJoin : unionWarNameList) {
                            if(unionJoin.getUnionUid().equals(groupUnion.getUnionUid())){
                                old = unionJoin;
                            }
                        }
                        if(old != null){
                            continue;
                        }
                        UnionWarUnionJoin name = new UnionWarUnionJoin();
                        name.setRankNum(groupUnion.getRank());
                        name.setActivityId(activityInfo.getActivityId());
                        name.setUnionUid(groupUnion.getUnionUid());
                        name.setUnionBaseInfo(unionBaseInfo);
                        name.setInsertOption();
                        name.setGroupId(groupId);
                        unionWarNameList.add(name);
                    }

                    logger.info("union war activity {}, groupId {} union list size {}", activityInfo.getActivityId(), groupId, unionWarNameList.size());
                    //初始化积分赛所有场次的备战基础数据
                    for (UnionWarUnionJoin nameList : unionWarNameList) {
                        CrossUnionServerGroup group = CrossUnionServerGroupMgr.getServerGroupByServerId(ConfigHelper.getLong("serverId"));
                        Set<Long> serverSet = new HashSet<>();
                        serverSet.add(ConfigHelper.getLong("serverId"));
                        if (group != null) {
                            serverSet.addAll(group.getServerList());
                        }
                        //只初始本分组的备战
                        if(nameList.getUnionBaseInfo() != null) {
                            if (!serverSet.contains(nameList.getUnionBaseInfo().getServerId())) {
                                continue;
                            }
                        }
                        Object lock = getUnionLocker(nameList.getUnionUid());
                        synchronized (lock) {
                            for (int session = 1; session <= getAllSession(1); session++) {
                                UnionWarDispatchDetail detail = checkAndGetUnionWarDispatchDetails(nameList.getUnionUid(), 1, session);
                                detail.setGroupId(groupId);
                                if(detail.getUnionInfo() == null){
                                    detail.setUnionInfo(nameList.getUnionBaseInfo());
                                }
                            }
                        }
                    }
                //}
                return;
            }
            List<UnionWarUnionJoin> syncList = new ArrayList<>();
            for (UnionWarUnionJoin nameList : unionWarNameList) {
                if (!nameList.isPushSuccess() || nameList.isNeedSync()) {
                    syncList.add(nameList);
                    nameList.setNeedSync(false);
                }
            }
            if (syncList.size() > 0) {
                List<String> unionUidList = new ArrayList<>();
                //推送跨服
                CrossUnionWarProto.CrossUnionWarJoinUnionListSyncMsg.Builder pushMsg = CrossUnionWarProto.CrossUnionWarJoinUnionListSyncMsg.newBuilder();
                for (UnionWarUnionJoin union : syncList) {
                    if(union.getUnionBaseInfo() == null){
                        UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(union.getUnionUid());
                        if(unionBaseInfo != null) {
                            union.setUnionBaseInfo(unionBaseInfo);
                        }
                    }
                    CrossUnionWarProto.CrossUnionWarJoinUnionTempMsg.Builder nameBuilder = CrossUnionWarProto.CrossUnionWarJoinUnionTempMsg.newBuilder();
                    nameBuilder.setUnionBaseTemp(UnionBasePb.parseUnionBaseTempMsg(union.getUnionBaseInfo()));
                    nameBuilder.setUnionUid(union.getUnionUid());
                    //nameBuilder.setRankNum(union.getRankNum());
                    pushMsg.addDataList(nameBuilder);
                    unionUidList.add(union.getUnionUid());
                }
                logger.info("union war activity {}, groupId {} push union size {},{}", activityInfo.getActivityId(), groupId, syncList.size(), StringUtils.listToString(unionUidList, ","));
                pushMsg.setActivityId(activityInfo.getActivityId());
                //GamePlayerMgr.sendChannelPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_CROSS_UNION_WAR_JOIN_UNION_SYNC, pushMsg));
                GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_UNION_WAR_JOIN_UNION_SYNC, pushMsg, 0, activityInfo.getActivityId(), groupId);
            }
        }
    }

    /**
     * 锁定每场战斗的商会成员(若停服还有问题)
     */
    public void lockUnionMember(String unionUid, int phase, int session) {
        if (!unionMemberMap.containsKey(unionUid)) {
            unionMemberMap.put(unionUid, new ConcurrentHashMap<>());
        }
        if (!unionMemberMap.get(unionUid).containsKey(phase)) {
            unionMemberMap.get(unionUid).put(phase, new ConcurrentHashMap<>());
        }
        if (!unionMemberMap.get(unionUid).get(phase).containsKey(session)) {
            UnionWarUnionMember warUnionMember = new UnionWarUnionMember();
            warUnionMember.setInsertOption();
            warUnionMember.setActivityId(activityInfo.getActivityId());
            warUnionMember.setPhase(phase);
            warUnionMember.setSession(session);
            warUnionMember.setUnionUid(unionUid);
            UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionUid);
            if (unionBaseInfo != null) {
                warUnionMember.setUnionBaseInfo(unionBaseInfo);
            }
            warUnionMember.setUserIdList(GameUnionActivityGroupMgr.getUnionUserList(activityInfo.getActivityId(), unionUid));
            unionMemberMap.get(unionUid).get(phase).put(session, warUnionMember);
            logger.info("union war activity{}, lock {} member size-{} in {} {}", activityInfo.getActivityId(), unionUid, warUnionMember.getUserIdList().size(), phase, session);
        }
    }

    /**
     * 检测并请求跨服战报
     */
    public void requestBattleResult(){
        CurrentTimeInfo currentTimeInfo = getCurrentTimeInfo();
        for(UnionQunyingTimeInfo period : timeInfoList){
            if(period.getSession() == 0){
                continue;
            }
            List<Integer> groupIdList = UnionWar.getGroupListByServerId(activityInfo.getActivityId(), GameServer.getInstance().getServerId());
            for (int groupId : groupIdList) {
                if(currentTimeInfo.getPeriodType() == eTimeInfoPeriodType.ReceiveTime){
                    requestCrossBattleResult(period.getType(), period.getSession(), groupId);
                }else if(currentTimeInfo.getTimeInfo() != null){
                    UnionQunyingTimeInfo currentPeriod = currentTimeInfo.getTimeInfo();
                    if(period.getType() > currentPeriod.getType()){
                        continue;
                    }
                    if(period.getType() == currentPeriod.getType() && period.getSession() > currentPeriod.getSession()){
                        continue;
                    }
                    requestCrossBattleResult(period.getType(), period.getSession(), groupId);
                }
            }
        }
    }

    private void requestCrossBattleResult(int phase, int session, int groupId) {
//        if(getCrossUnionWarBattleResult(phase, session, groupId) != null){
//            return;
//        }
        List<UnionWarActivityServerProto.MatchVideoBattleTemp> list = getMatchVideoBattleTempList(phase, session, groupId);
        if(list != null && list.size() > 0){
            return;
        }
        UnionWarActivityServerProto.RequestCrossBattleDataReqMsg.Builder reqMsg = UnionWarActivityServerProto.RequestCrossBattleDataReqMsg.newBuilder();
        reqMsg.setActivityId(activityInfo.getActivityId());
        reqMsg.setPhase(phase);
        reqMsg.setSession(session);
        reqMsg.setGroupId(groupId);
        //精彩对阵和战斗结果  需要按分组
        //GamePlayerMgr.sendChannelPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_CROSS_UNION_WAR_REQUEST_BATTLE_RESULT, reqMsg));
        GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_UNION_WAR_REQUEST_BATTLE_RESULT, reqMsg, 0, activityInfo.getActivityId(), groupId);
    }

    /**
     * 推送参赛资格跨服响应
     * @param unionUidListList
     */
    public void syncNameListResponseFromCross(List<String> unionUidListList) {
        for (Map.Entry<Integer, List<UnionWarUnionJoin>> entry : unionWarNameListMap.entrySet()) {
            for (int i = 0; i < entry.getValue().size(); i++) {
                UnionWarUnionJoin nameList = entry.getValue().get(i);
                if(unionUidListList.contains(nameList.getUnionUid())){
                    nameList.setPushSuccess(true);
                }
            }
        }
    }

    public void syncAllUnionDetailFromCross(UnionWarActivityServerProto.CrossUnionWarDetailSync syncMsg) {
        syncUnionDetailFromCross(syncMsg);
        requestCrossDetail = true;
    }

    public void syncUnionDetailFromCross(UnionWarActivityServerProto.CrossUnionWarDetailSync syncMsg) {
        for (UnionWarActivityServerProto.CrossUnionWarDetailTemp detailTempMsg : syncMsg.getDetailList()) {
            String unionUid = detailTempMsg.getUnionUid();
            UnionWarUnionJoin unionWarUnionJoin = getUnionWarNameList(unionUid);
            if(unionWarUnionJoin != null){
                if (Objects.equals(unionUid, unionWarUnionJoin.getUnionUid())) {
                    if (!unionDispatchDetailMap.containsKey(detailTempMsg.getUnionUid())) {
                        unionDispatchDetailMap.put(detailTempMsg.getUnionUid(), new ConcurrentHashMap<>());
                    }
                    Map<Integer, Map<Integer, UnionWarDispatchDetail>> phaseDetailMap = unionDispatchDetailMap.get(detailTempMsg.getUnionUid());

                    if (!phaseDetailMap.containsKey(detailTempMsg.getStageNo())) {
                        phaseDetailMap.put(detailTempMsg.getStageNo(), new ConcurrentHashMap<>());
                    }
                    Map<Integer, UnionWarDispatchDetail> sessionMap = phaseDetailMap.get(detailTempMsg.getStageNo());
                    if (sessionMap.containsKey(detailTempMsg.getRoundNo())) {
                        UnionWarDispatchDetail newDetail = newDetail(detailTempMsg, detailTempMsg.getStageNo(), detailTempMsg.getRoundNo());
                        newDetail.setGroupId(detailTempMsg.getGroupId());
                        UnionWarDispatchDetail detail = sessionMap.get(detailTempMsg.getRoundNo());
                        reBuildDetail(detail, newDetail);
                    }
                    break;
                }
            }
        }
    }

    //重构
    private void reBuildDetail(UnionWarDispatchDetail detail, UnionWarDispatchDetail newDetail) {
        Map<Long, UnionWarUserPatrons> patronsMap = detail.getPatronsMap();
        Map<Long, UnionWarUserSilver> silverMap = detail.getSilverMap();
        Map<Long, UserBaseInfo> userBaseInfoMap = detail.getUserBaseInfoMap();

        List<Long> needUpdateUserIdList = new ArrayList<>();
        for (Map.Entry<Long, UserBaseInfo> entry : newDetail.getUserBaseInfoMap().entrySet()) {
            if (entry.getValue().getServerId() == GameServer.getInstance().getServerId()) {
                continue;
            }
            needUpdateUserIdList.add(entry.getKey());
        }
        for (Long userId : needUpdateUserIdList) {
            //保留backGoods字段
            UnionWarUserPatrons newPatrons = newDetail.getPatronsMap().get(userId);
            UnionWarUserPatrons oldPatrons = detail.getPatronsMap().get(userId);
            if(newPatrons != null && oldPatrons != null){
                newPatrons.setBackGoods(oldPatrons.isBackGoods());
            }
            patronsMap.put(userId, newDetail.getPatronsMap().get(userId));
            silverMap.put(userId, newDetail.getSilverMap().get(userId));
            userBaseInfoMap.put(userId, newDetail.getUserBaseInfoMap().get(userId));
        }
        detail.setUnionUid(newDetail.getUnionUid());
        detail.setEnemyUnionUid(newDetail.getEnemyUnionUid());
        detail.setEnemyUnionInfo(newDetail.getEnemyUnionInfo());
        detail.setWinMark(newDetail.getWinMark());
        detail.setGroupId(newDetail.getGroupId());
        detail.setUpdateOption();
    }

    private UnionWarDispatchDetail newDetail(UnionWarActivityServerProto.CrossUnionWarDetailTemp detailTempMsg, int phase, int session) {
        UnionWarDispatchDetail detail = new UnionWarDispatchDetail();
        detail.setActivityId(activityInfo.getActivityId());
        detail.setUnionUid(detailTempMsg.getUnionUid());
        detail.setPhase(phase);
        detail.setSession(session);
        Map<Long, UnionWarUserPatrons> patronsMap = new ConcurrentHashMap<>();
        Map<Long, UnionWarUserSilver> silverMap = new ConcurrentHashMap<>();
        Map<Long, UserBaseInfo> userBaseInfoMap = new ConcurrentHashMap<>();
        for (CrossUnionWarProto.CrossUnionWarUserDetailTempMsg userDetailTempMsg : detailTempMsg.getUserDataListList()) {
            //派遣门客
            UnionWarUserPatrons userPatrons = new UnionWarUserPatrons();
            userPatrons.setServerId(userDetailTempMsg.getServerId());
            userPatrons.setUserId(userDetailTempMsg.getUserId());
            userPatrons.setGoodsId(userDetailTempMsg.getUseItemId());
            userPatrons.setPosition(userDetailTempMsg.getUnionPosition());
            userPatrons.setSendTime(userDetailTempMsg.getSendTime());
            Map<Integer, UnionWarUserPatronsDetail> patrons = new ConcurrentHashMap<>();
            for (CrossUnionWarProto.CrossUnionWarPatronsTempMsg patronsTempMsg : userDetailTempMsg.getPatronsDataListList()) {
                UnionWarUserPatronsDetail patronsDetail = new UnionWarUserPatronsDetail();
                patronsDetail.setPatronsId(patronsTempMsg.getPatronsId());
                patronsDetail.setPatronsLv(patronsTempMsg.getPatronsLv());
                patronsDetail.setPatronsStageLv(patronsTempMsg.getPatronsStageLv());
                patronsDetail.setSkinId(patronsTempMsg.getSkinId());
                patronsDetail.setType(patronsTempMsg.getAmbush());
                patronsDetail.setPromotionId((int) patronsTempMsg.getPromotionId());
                patronsDetail.setAbility(new BigInteger(patronsTempMsg.getAbility()).longValue());
                patronsDetail.setSkillAddition(patronsTempMsg.getSkillAddition());
                patronsDetail.setLianShengAddition(patronsTempMsg.getLianShengAddition());
                patronsDetail.setAbility2(UnionPhaseWarMgr.unionPositionAndSkillEffectPatronsData(patronsDetail.getAbility(), userDetailTempMsg.getUnionPosition(), activityInfo, patronsDetail.getSkillAddition()));
                patrons.put(patronsDetail.getPatronsId(), patronsDetail);
            }
            userPatrons.setPatrons(patrons);
            patronsMap.put(userPatrons.getUserId(), userPatrons);

            //募捐
            UnionWarUserSilver silver = new UnionWarUserSilver();
            silver.setServerId(userDetailTempMsg.getServerId());
            silver.setUserId(userDetailTempMsg.getUserId());
            silver.setSilver(new BigInteger(userDetailTempMsg.getDonateSilver()));
            silver.setQuit(userDetailTempMsg.getIsQuitUnion());
            silver.setNickName(userDetailTempMsg.getUserBaseInfo().getNickName());
            silver.setPosition(userDetailTempMsg.getUnionPosition());
            silverMap.put(silver.getUserId(), silver);

            //玩家详情
            userBaseInfoMap.put(userDetailTempMsg.getUserId(), PlayerBasePb.parseBaseUserInfo(userDetailTempMsg.getUserBaseInfo()));
        }
        detail.setPatronsMap(patronsMap);
        detail.setSilverMap(silverMap);
        detail.setUserBaseInfoMap(userBaseInfoMap);
        detail.setEnemyUnionUid(detailTempMsg.getEnemyUnionUid());
        if (detailTempMsg.getEnemyUnionInfo() != null) {
            detail.setEnemyUnionInfo(UnionBasePb.parseUnionBaseInfo(detailTempMsg.getEnemyUnionInfo()));
        }
        detail.setWinMark(detailTempMsg.getWinMark());
        return detail;
    }

    /**
     * 是否可解散商会
     * @param unionUid
     * @return
     */
    public boolean canDeleteUnion(String unionUid) {
        if(ActivityMgr.activityInShowTime(activityInfo)){
            UnionWarUnionJoin unionJoin = getUnionWarNameList(unionUid);
            if(unionJoin != null){
                return false;
            }
        }
        return true;
    }

    public void requestCrossSyncDetail() {
        if (!requestCrossDetail) {
            CurrentTimeInfo currentTimeInfo = getCurrentTimeInfo();
            if (currentTimeInfo == null) {
                requestCrossDetail = true;
                return;
            }
            UnionWarActivityServerProto.ReqCrossSyncDetailMsg.Builder reqCrossMsg = UnionWarActivityServerProto.ReqCrossSyncDetailMsg.newBuilder();
            reqCrossMsg.setActivityId(activityInfo.getActivityId());
            for (Map.Entry<Integer, List<UnionWarUnionJoin>> listEntry : unionWarNameListMap.entrySet()) {
                List<String> unionUidList = listEntry.getValue().stream().map(UnionWarUnionJoin::getUnionUid).collect(Collectors.toList());
                reqCrossMsg.addAllUnionUid(unionUidList);
                //YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UNION_WAR_REQ_SYNC_DETAIL, reqCrossMsg);
                //GamePlayerMgr.sendChannelPacket(0, message);
                GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_UNION_WAR_REQ_SYNC_DETAIL, reqCrossMsg, 0, activityInfo.getActivityId(), listEntry.getKey());
            }
        }
    }

    /**
     * 同步备战数到跨服
     */
    public void syncUnionWarPrepareData(){
        CurrentTimeInfo currentTimeInfo = getCurrentTimeInfo();
        long now = System.currentTimeMillis();
        if(currentTimeInfo.getTimeInfo() != null){
            UnionQunyingTimeInfo timeInfo = currentTimeInfo.getTimeInfo();
            List<Integer> groupIdList = getGroupListByServerId(activityInfo.getActivityId(), GameServer.getInstance().getServerId());
            for (Integer groupId : groupIdList) {
                List<String> unionUidList = getGroupUnionUidList(activityInfo.getActivityId(), groupId);
                Map<Integer, Map<Integer, List<UnionWarDispatchDetail>>> syncMap = new HashMap<>();  //按场次批量更新所有商会数据
                for (Map.Entry<String, Map<Integer, Map<Integer, UnionWarDispatchDetail>>> unionEntry : unionDispatchDetailMap.entrySet()) {
                    for (Map.Entry<Integer, Map<Integer, UnionWarDispatchDetail>> phaseEntry : unionEntry.getValue().entrySet()) {
                        int phase = phaseEntry.getKey();
                        if (phase != timeInfo.getType()) {
                            continue;
                        }
                        for (Map.Entry<Integer, UnionWarDispatchDetail> sessionEntry : phaseEntry.getValue().entrySet()) {
                            int session = sessionEntry.getKey();
                            if (session < timeInfo.getSession()) {
                                continue;
                            }
                            UnionWarDispatchDetail detail = sessionEntry.getValue();
                            //有修改（捐钱、派遣、锦囊有操作）就上传
                            if(unionUidList.size() > 0 && !unionUidList.contains(detail.getUnionUid())){
                                continue;
                            }
                            if (detail.getLastUpdateTime() > detail.getLastPushTime()) {
                                if (!syncMap.containsKey(detail.getPhase())) {
                                    syncMap.put(detail.getPhase(), new HashMap<>());
                                }
                                if (!syncMap.get(detail.getPhase()).containsKey(detail.getSession())) {
                                    syncMap.get(detail.getPhase()).put(detail.getSession(), new ArrayList<>());
                                }
                                syncMap.get(detail.getPhase()).get(detail.getSession()).add(detail);
                                synchronized (detail) {
                                    detail.setLastPushTime(now);
                                }
                            }
                        }
                    }
                }
                for(Map.Entry<Integer, Map<Integer, List<UnionWarDispatchDetail>>> phaseEntry : syncMap.entrySet()){
                    for(Map.Entry<Integer, List<UnionWarDispatchDetail>> sessionEntry : phaseEntry.getValue().entrySet()) {
                        CrossUnionWarProto.CrossUnionWarDetailSyncMsg.Builder pushMsg = CrossUnionWarProto.CrossUnionWarDetailSyncMsg.newBuilder();
                        pushMsg.setActivityId(activityInfo.getActivityId());
                        pushMsg.setPhase(phaseEntry.getKey());
                        pushMsg.setSession(sessionEntry.getKey());
                        for (UnionWarDispatchDetail detail : sessionEntry.getValue()) {
                            pushMsg.addUnionDataList(UnionWarActivityPb.parseCrossUnionWarUnionDetailTempMsg(detail, GameServer.getInstance().getServerId()));
                        }
                        //GamePlayerMgr.sendChannelPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_CROSS_UNION_WAR_DETAIL_SYNC, pushMsg));
                        GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_UNION_WAR_DETAIL_SYNC, pushMsg, 0, activityInfo.getActivityId(), groupId);
                        logger.info("union war activity {}, groupId {} push prepare data size {} in {} {}", activityInfo.getActivityId(), groupId, sessionEntry.getValue().size(), phaseEntry.getKey(), sessionEntry.getKey());
                    }
                }
            }
        }
    }

    /**
     * 新增战斗明细(同时处理精彩对阵)
     * @param phase
     * @param session
     * @param temp
     */
    public void addCrossUnionWarBattleResult(int phase, int session, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg temp, int groupId) {
        if(temp.getIsTopMatch()){
            addMatchVideoBattleTemp(phase, session, temp);
        }
        //锁定本服商会成员（战斗期）
        lockUnionMember(temp.getUnionUid(), phase, session);
        UnionWarDispatchDetail detail = getUnionWarDispatchDetailList(temp.getUnionUid(), phase, session);
        if (detail != null) {
            UnionBaseInfo unionInfo = CrossUnionMgr.parseUnionBaseInfo(temp.getUnionUid());
            if(unionInfo != null) {
                detail.setUnionInfo(unionInfo);
            }
        }
    }

    /**
     * 增加精彩对阵
     * @param phase
     * @param session
     * @param temp
     */
    private void addMatchVideoBattleTemp(int phase, int session, CrossUnionWarProto.CrossUnionWarUnionBattleTempMsg temp) {
        if(temp.getWinMark() != eUnionWarWinMark.Win.getValue()){
            //去重，只用胜利方
            return;
        }
        Map<Integer, Map<String, UnionWarActivityServerProto.MatchVideoBattleTemp>> sessionMap = matchVideoBattleMap.get(phase);
        if(sessionMap == null){
            synchronized (matchVideoBattleMap){
                sessionMap = matchVideoBattleMap.get(phase);
                if(sessionMap == null){
                    sessionMap = new ConcurrentHashMap<>();
                    matchVideoBattleMap.put(phase, sessionMap);
                }
            }
        }
        Map<String, UnionWarActivityServerProto.MatchVideoBattleTemp> unionMap = sessionMap.get(session);
        if(unionMap == null){
            synchronized (sessionMap){
                unionMap = sessionMap.get(session);
                if(unionMap == null){
                    unionMap = new ConcurrentHashMap<>();
                    sessionMap.put(session, unionMap);
                }
            }
        }
        if(!unionMap.containsKey(temp.getUnionUid())){
            UnionWarActivityServerProto.MatchVideoBattleTemp.Builder builder = UnionWarActivityServerProto.MatchVideoBattleTemp.newBuilder();
            builder.setNo(temp.getNo());
            builder.setWinMark(temp.getWinMark());
            builder.setUnionUid(temp.getUnionUid());
            builder.setUnionInfo(temp.getUnionBaseInfo());
            builder.setEnemyUnionUid(temp.getEnemyUnionUid());
            builder.setEnemyUnionInfo(temp.getEnemyUnionBaseInfo());
            builder.setSession(session);
            //v2.6
            builder.setTeamEarnSpeed(temp.getTeamEarnSpeed());
            builder.setEnemyTeamEarnSpeed(temp.getEnemyTeamEarnSpeed());
            unionMap.put(temp.getUnionUid(), builder.build());
        }
    }

    /**
     * 备战界面概览（备战列表/我的商会战况）
     * @param player
     * @param unionUid
     * @param beginSession
     * @param endSession
     * @return
     */
    public int prepareOverview(GamePlayer player, String unionUid, int phase, int beginSession, int endSession) {
        boolean join = isJoin(unionUid);
        if(!join){
            return GameErrorCode.E_ACTIVITY_NO_JOIN;
        }
        if(endSession == 0){
            endSession = getAllSession(phase);
        }
        if(beginSession == 0){
            beginSession = 1;
        }
        UnionWarActivityServerProto.PrepareOverviewRespMsg.Builder respMsg = UnionWarActivityServerProto.PrepareOverviewRespMsg.newBuilder();
        respMsg.setActivityId(activityInfo.getActivityId());
        respMsg.setPhase(phase);
        respMsg.setBeginSession(beginSession);
        respMsg.setEndSession(endSession);
        respMsg.setRet(0);

        List<UnionWarDispatchDetail> list = new ArrayList<>();

        //需求变更：决赛需要积分赛的数据
        //if(phase == 2){
        //    Map<Integer, UnionWarDispatchDetail> detailMap = getUnionWarDispatchDetailList(unionUid, 1);
        //    if(detailMap != null) {
        //        for(int session : detailMap.keySet()){
        //            list.add(detailMap.get(session));
        //        }
        //    }
        //}
        Map<Integer, UnionWarDispatchDetail> detailMap = getUnionWarDispatchDetailList(unionUid, phase);
        if(detailMap != null) {
            for(int session : detailMap.keySet()){
                if(session >= beginSession && session <= endSession){
                    list.add(detailMap.get(session));
                }
            }
        }
        if(list.size() > 0){
            for(UnionWarDispatchDetail detail : list){
                UnionBaseInfo unionInfo = CrossUnionMgr.parseUnionBaseInfo(detail.getUnionUid());
                UnionWarActivityServerProto.SessionLineupTemp.Builder tempBuilder = UnionWarActivityPb.parseSessionLineupTempList(detail, false, getCanDispatchMemberList(detail.getUnionUid()).size(), detail.getEnemyUnionInfo(), unionInfo);
                if(detail.getPatronsMap().containsKey(player.getUserId())){
                    tempBuilder.setSend(true);
                }else{
                    tempBuilder.setSend(false);
                }
                if(detail.getWinMark() == eUnionWarWinMark.Bye.getValue()){
                    UnionWarSessionReward reward = player.getModule(UnionWarActivityModule.class).getBattleReward(activityInfo.getActivityId(), detail.getPhase(), detail.getSession());
                    if(reward == null){
                        tempBuilder.setGetByeReward(false);
                    }else {
                        tempBuilder.setGetByeReward(true);
                    }
                }
                respMsg.addLineupList(tempBuilder);
            }
        }
        player.sendPacket(Protocol.U_UNION_WAR_PREPARE_OVERVIEW, respMsg);
        return 0;
    }


    public List<Long> getCanDispatchMemberList(String unionUid) {
        List<Long> canDispatchList = new ArrayList<>();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return canDispatchList;
        }
//        Map<Integer, Map<Integer, UnionWarUnionMember>> memberMap = unionMemberMap.get(unionUid);
//        if (memberMap != null) {
//            Map<Integer, UnionWarUnionMember> phaseMap = memberMap.get(1);
//            if (phaseMap != null) {
//                UnionWarUnionMember sessionMap = phaseMap.get(1);
//                if (sessionMap != null) {
//                    canDispatchList.addAll(sessionMap.getUserIdList());
//                }
//            }
//        }

        List<Long> unionMemberUserIdList = new ArrayList<>();
        UnionActivityGroupUnion groupUnion = GameUnionActivityGroupMgr.getUnionData(activityInfo.getActivityId(), unionUid);
        if(groupUnion != null){
            for (Map.Entry<Long, UnionActivityGroupUser> entry : groupUnion.getUserMap().entrySet()) {
                unionMemberUserIdList.add(entry.getKey());
            }
            canDispatchList.addAll(unionMemberUserIdList);
        }
//        Map<Integer, Map<Integer, UnionWarDispatchDetail>> map = getUnionWarDispatchDetailList(unionUid);
//        if (map != null) {
//            for (Map<Integer, UnionWarDispatchDetail> detailMap : map.values()) {
//                for (UnionWarDispatchDetail detail : detailMap.values()) {
//                    for (Long userId : detail.getPatronsMap().keySet()) {
//                        if (!canDispatchList.contains(userId) && unionMemberUserIdList.contains(userId)) {
//                            canDispatchList.add(userId);
//                        }
//                    }
//                }
//            }
//        }
        return canDispatchList;
    }

    /**
     * 阵容未派遣的成员
     * @param player
     * @param unionUid
     * @param phase
     * @param session
     * @return
     */
    @Deprecated
    public int getNoDispatchMember(GamePlayer player, String unionUid, int phase, int session) {
        boolean join = isJoin(unionUid);
        if(!join){
            return GameErrorCode.E_ACTIVITY_NO_JOIN;
        }
        UnionWarActivityServerProto.UnionWarGetNoDispatchMemberRespMsg.Builder respMsg = UnionWarActivityServerProto.UnionWarGetNoDispatchMemberRespMsg.newBuilder();
        respMsg.setActivityId(activityInfo.getActivityId());
        respMsg.setPhase(phase);
        respMsg.setSession(session);
        respMsg.setRet(0);

        UnionWarDispatchDetail detail = getUnionWarDispatchDetailList(unionUid, phase, session);
        List<Long> unionMemberList = getCanDispatchMemberList(unionUid);
        if(detail != null && unionMemberList != null){
            List<Long> sendList = new ArrayList<>();
            for(Map.Entry<Long, UnionWarUserPatrons> teamUserPatronsEntry : detail.getPatronsMap().entrySet()){
                long userId = teamUserPatronsEntry.getKey();
                UnionWarUserPatrons teamUserPatrons = teamUserPatronsEntry.getValue();
                if(teamUserPatrons.getPatrons().size() > 0) { //有门客
                    sendList.add(userId);
                }
            }
            for(Long userId : unionMemberList){
                if(!sendList.contains(userId)){
                    UnionWarActivityServerProto.UnionWarUnionMember.Builder builder = UnionWarActivityServerProto.UnionWarUnionMember.newBuilder();
                    builder.setUserId(userId);
                    CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(userId);
                    if (unionMember == null) {
                        continue;
                    }
                    builder.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(unionMember.getUserBaseInfo()));
                    respMsg.addMember(builder);
                }
            }
        }
        player.sendPacket(Protocol.U_UNION_WAR_PREPARE_NO_DISPATCH_MEMBER, respMsg);
        return 0;
    }


    /**
     * 备战界面详情
     * @param player
     * @param unionUid
     * @param phase
     * @param session
     * @return
     */
    public int prepareDetail(GamePlayer player, String unionUid, int phase, int session) {
        boolean join = isJoin(unionUid);
        if(!join){
            return GameErrorCode.E_ACTIVITY_NO_JOIN;
        }

        UnionWarActivityServerProto.PrepareDetailRespMsg.Builder respMsg = UnionWarActivityServerProto.PrepareDetailRespMsg.newBuilder();
        respMsg.setActivityId(activityInfo.getActivityId());
        respMsg.setPhase(phase);
        respMsg.setSession(session);
        respMsg.setRet(0);

        UnionWarDispatchDetail detail = getUnionWarDispatchDetailList(unionUid, phase, session);
        if(detail != null){
            UnionBaseInfo unionInfo = CrossUnionMgr.parseUnionBaseInfo(detail.getUnionUid());
            UnionWarActivityServerProto.SessionLineupTemp.Builder builder = UnionWarActivityPb.parseSessionLineupTempList(detail, true, getCanDispatchMemberList(detail.getUnionUid()).size(), detail.getEnemyUnionInfo(), unionInfo);
            respMsg.setLineupList(builder);
        }
        player.sendPacket(Protocol.U_UNION_WAR_PREPARE_DETAIL, respMsg);
        return 0;
    }

    /**
     * 获取活动商会锁
     * @param unionUid
     * @return
     */
    public Object getUnionLocker(String unionUid){
        if(!unionLocker.containsKey(unionUid)){
            synchronized (unionLocker){
                if(!unionLocker.containsKey(unionUid)) {
                    unionLocker.put(unionUid, new Object());
                }
            }
        }
        return unionLocker.get(unionUid);
    }

    /**
     * 获取活动玩家锁
     * @param userId
     * @return
     */
    public Object getUserLocker(long userId){
        if(!userLocker.containsKey(userId)){
            synchronized (userLocker){
                if(!userLocker.containsKey(userId)) {
                    userLocker.put(userId, new Object());
                }
            }
        }
        return userLocker.get(userId);
    }

    /**
     * 检查初始备战数据（需放在活动商会锁中）
     * @param unionUid
     * @param phase
     * @param session
     * @return
     */
    public UnionWarDispatchDetail checkAndGetUnionWarDispatchDetails(String unionUid, int phase, int session) {
        UnionWarDispatchDetail detail;
        if(!unionDispatchDetailMap.containsKey(unionUid)){
            unionDispatchDetailMap.put(unionUid, new ConcurrentHashMap<>());
        }
        if(!unionDispatchDetailMap.get(unionUid).containsKey(phase)){
            unionDispatchDetailMap.get(unionUid).put(phase, new ConcurrentHashMap<>());
        }
        if(!unionDispatchDetailMap.get(unionUid).get(phase).containsKey(session)){
            detail = new UnionWarDispatchDetail();
            initDispatchDetail(unionUid, phase, session, detail);
            unionDispatchDetailMap.get(unionUid).get(phase).put(session, detail);
        }else {
            detail = unionDispatchDetailMap.get(unionUid).get(phase).get(session);
        }
        return detail;
    }

    public int dispatchUserGoods(GamePlayer player, String unionUid, int phase, int session, int goodsId) {
        //是否参与活动
        boolean join = isJoinCurrentTimeInfo(unionUid, null);
        if(!join){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_NO_JOIN_SESSION;
        }
        //周期检测
        int ret = checkTimeInfoInPrepareTime(phase, session);
        if(ret != 0){
            return ret;
        }
        Object locker = getUnionLocker(unionUid);
        UnionWarDispatchDetail detail;
        //synchronized (locker) {
        //    detail = checkAndGetUnionWarDispatchDetails(unionUid, phase, session);
        //}
        detail = getUnionWarDispatchDetailList(unionUid, phase, session);
        if(detail == null){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_NO_JOIN_SESSION;
        }

        int oldGoodsId;
        UnionWarUserPatrons unionWarUserPatrons;
        synchronized (getUserLocker(player.getUserId())){
            unionWarUserPatrons = detail.getPatronsMap().get(player.getUserId());
            if(unionWarUserPatrons == null){
                unionWarUserPatrons = new UnionWarUserPatrons();
                unionWarUserPatrons.setServerId(GameServer.getInstance().getServerId());
                unionWarUserPatrons.setUserId(player.getUserId());
                unionWarUserPatrons.setSendTime(System.currentTimeMillis());
            }
            oldGoodsId = unionWarUserPatrons.getGoodsId();
            if(goodsId > 0){
                Property goodsProperty = new Property(goodsId, BigInteger.ONE);
                if(!player.getModule(CurrencyModule.class).removeCurrency(goodsProperty, eLogMoneyType.Activity, eLogMoneyType.UnionWarActivityGoodsUse)){
                    return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                }
            }
            if(oldGoodsId > 0){
                Property goodsProperty = new Property(oldGoodsId, BigInteger.ONE);
                player.getModule(CurrencyModule.class).addCurrency(goodsProperty, eLogMoneyType.Activity, eLogMoneyType.UnionWarActivityGoodsUseGiveBack);
                try {
                    //道具使用日志
                    AutoLogMgr.add(new LogUnionWarActivityGoodsUse(player.getUserId(), activityInfo.getActivityId(), oldGoodsId, phase, session, -1));
                }catch (Exception e){
                    logger.error(e.getMessage(), e);
                }
            }
        }
        //撤回门客、珍兽
        String backVehicle = null;
        int backFish = 0;
        int backPatronsId = 0;
        synchronized (detail){
            //职位
            UnionActivityGroupUnion groupUnion = GameUnionActivityGroupMgr.getUnionData(activityInfo.getActivityId(), unionUid);
            if(groupUnion != null) {
                UnionActivityGroupUser groupUser = groupUnion.getUserMap().get(player.getUserId());
                if(groupUser != null) {
                    unionWarUserPatrons.setPosition(groupUser.getPosition());
                }
            }
            if(goodsId >= 0){
                unionWarUserPatrons.setGoodsId(goodsId);
            }
            if(oldGoodsId == eItemId.UNION_WAR_ACTIVITY_SMFB_JN.getValue() && goodsId != eItemId.UNION_WAR_ACTIVITY_SMFB_JN.getValue()){
                //取消伏兵
                for(Map.Entry<Integer, UnionWarUserPatronsDetail> entry : unionWarUserPatrons.getPatrons().entrySet()){
                    UnionWarUserPatronsDetail patronsDetail = entry.getValue();
                    if(patronsDetail.getType() == 1){
                        unionWarUserPatrons.getPatrons().remove(patronsDetail.getPatronsId());
                        backPatronsId = patronsDetail.getPatronsId();
                        backVehicle = unionWarUserPatrons.getVehicleUidList().remove(patronsDetail.getPatronsId());
                        if (unionWarUserPatrons.getFishIdList().containsKey(patronsDetail.getPatronsId())) {
                            backFish = unionWarUserPatrons.getFishIdList().remove(patronsDetail.getPatronsId());
                        }
                        break;
                    }
                }
            }
            detail.putPatrons(player.getUserId(), unionWarUserPatrons);
            //玩家信息
            detail.putUserBaseInfo(player.getUserId(), UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId()));
            detail.setLastUpdateTime(System.currentTimeMillis());
        }
        synchronized (getUserLocker(player.getUserId())){
            //出战次数返还
            if(backPatronsId > 0) {
                UserPatronsSendTimes patronsSendTimes = getUserPatronsSend(player.getUserId(), backPatronsId);
                if (patronsSendTimes != null && patronsSendTimes.getTimes() > 0) {
                    patronsSendTimes.setTimes(patronsSendTimes.getTimes() - 1);
                }
            }
            if(backVehicle != null){
                UserVehicleSendTimes vehicleSendTimes = getUserVehicleSend(player.getUserId(), backVehicle);
                if(vehicleSendTimes != null && vehicleSendTimes.getTimes() > 0) {
                    vehicleSendTimes.setTimes(vehicleSendTimes.getTimes() - 1);
                }
            }
            if (backFish != 0) {
                UserFishSendTimes fishSendTimes = getUserFishSend(player.getUserId(), backFish);
                if (fishSendTimes != null && fishSendTimes.getTimes() > 0) {
                    fishSendTimes.setTimes(fishSendTimes.getTimes() - 1);
                }
            }
        }

        try {
            if(goodsId > 0) {
                //道具使用日志
                AutoLogMgr.add(new LogUnionWarActivityGoodsUse(player.getUserId(), activityInfo.getActivityId(), goodsId, phase, session, 1));
            }
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
        //返回消息
        UnionWarActivityServerProto.UserDispatchRespMsg.Builder respMsg = UnionWarActivityServerProto.UserDispatchRespMsg.newBuilder();
        UnionBaseInfo unionInfo = CrossUnionMgr.parseUnionBaseInfo(detail.getUnionUid());
        respMsg.setLineupInfo(UnionWarActivityPb.parseSessionLineupTempList(detail, true, getCanDispatchMemberList(detail.getUnionUid()).size(), detail.getEnemyUnionInfo(), unionInfo));
        respMsg.setRet(0);
        respMsg.setPhase(phase);
        respMsg.setSession(session);
        player.sendPacket(Protocol.U_UNION_WAR_USER_GOODS_USE, respMsg);
        return 0;
    }

    /**
     * 派遣门客
     * @param player
     * @param unionUid
     * @param phase
     * @param session
     * @param patronsIdList
     * @return
     */
    public int dispatchPatrons(GamePlayer player, String unionUid, int phase, int session, List<Integer> patronsIdList) {
        //是否参与活动
        boolean join = isJoinCurrentTimeInfo(unionUid, null);
        if(!join){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_NO_JOIN_SESSION;
        }
        //周期检测
        int ret = checkTimeInfoInPrepareTime(phase, session);
        if(ret != 0){
            return ret;
        }
        Object locker = getUnionLocker(unionUid);
        UnionWarDispatchDetail detail;
        //synchronized (locker) {
        //    detail = checkAndGetUnionWarDispatchDetails(unionUid, phase, session);
        //}
        detail = getUnionWarDispatchDetailList(unionUid, phase, session);
        if(detail == null){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_NO_JOIN_SESSION;
        }
        if (!getCanDispatchMemberList(unionUid).contains(player.getUserId())) {
            return GameErrorCode.E_UNION_WAR_ACTIVITY_NO_JOIN_SESSION;
        }

        Object userLocker = getUserLocker(player.getUserId());
        UnionWarUserPatrons unionWarUserPatrons;
        Map<Integer, UnionWarUserPatronsDetail> newPatronsDetail = new HashMap<>();
        Map<Integer, String> newVehicle = new HashMap<>();
        Map<Integer, Integer> newFish = new HashMap<>();
        Map<Integer, Integer> newCricket = new HashMap<>();
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        int position = GameUnionActivityGroupMgr.getUnionPosition(activityInfo.getActivityId(), player.getUserId());
        synchronized (userLocker){
            unionWarUserPatrons = detail.getPatronsMap().get(player.getUserId());
            if(unionWarUserPatrons == null){
                unionWarUserPatrons = new UnionWarUserPatrons();
                unionWarUserPatrons.setServerId(GameServer.getInstance().getServerId());
                unionWarUserPatrons.setUserId(player.getUserId());
                unionWarUserPatrons.setSendTime(System.currentTimeMillis());//派遣后保持不变
            }else {     //4.5又改为派遣后刷新派遣时间
                unionWarUserPatrons.setSendTime(System.currentTimeMillis());//v2.6
            }
            Set<Integer> oldPatrons = unionWarUserPatrons.getPatrons().keySet();
            for(int patronsId : patronsIdList) {
                if (patronsId > 0) {
                    //门客、珍兽派遣次数检测
                    UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
                    if (userPatrons == null) {
                        return GameErrorCode.E_PATRONS_NO_FOUND;
                    }
                    UserPatronsSendTimes sendTimes = getUserPatronsSend(player.getUserId(), patronsId);
                    if (sendTimes != null && sendTimes.getTimes() >= DISPATCH_TIMES && !oldPatrons.contains(patronsId)) {
                        return GameErrorCode.E_UNION_WAR_ACTIVITY_PATRONS_OVER_LIMIT;
                    }
                    //原装备的珍兽
                    String oldVehicle = unionWarUserPatrons.getVehicleUidList().get(patronsId);
                    //现装备的珍兽
                    UserVehicle userVehicle = player.getModule(VehicleModule.class).getEquipVehicle(patronsId);
                    if(userVehicle != null){
                        UserVehicleSendTimes vehicleSendTimes = getUserVehicleSend(player.getUserId(), userVehicle.getVehicleUid());
                        if (vehicleSendTimes != null && vehicleSendTimes.getTimes() >= DISPATCH_TIMES && !userVehicle.getVehicleUid().equals(oldVehicle)) {
                            return GameErrorCode.E_UNION_WAR_ACTIVITY_VEHICLE_OVER_LIMIT;
                        }
                    }

                    //原装备的鱼类
                    int oldFish = 0;
                    if (unionWarUserPatrons.getFishIdList().containsKey(patronsId)) {
                        oldFish = unionWarUserPatrons.getFishIdList().get(patronsId);
                    }
                    //现装备的鱼类
                    Map<Integer, FishData> fishDataMap = player.getModule(ManorModule.class).getManorFishPondModel().getFishDataMap();
                    FishData fishData = FishPondMgr.getUserFishByPatrons(patronsId, fishDataMap);
                    if(fishData != null){
                        UserFishSendTimes fishSendTimes = getUserFishSend(player.getUserId(), fishData.getFishId());
                        if (fishSendTimes != null && fishSendTimes.getTimes() >= DISPATCH_TIMES && fishData.getFishId() != oldFish) {
                            return GameErrorCode.E_UNION_WAR_ACTIVITY_FISH_OVER_LIMIT;
                        }
                    }
                }
            }
            Collection<String> oldVehicleList = unionWarUserPatrons.getVehicleUidList().values();
            Collection<Integer> oldFishList = unionWarUserPatrons.getFishIdList().values();
            Collection<Integer> oldCricketList = unionWarUserPatrons.getCricketIdList().values();

            //重置新出战次数
            int i = 1;
            for(int patronsId : patronsIdList) {
                //没有伏兵锦囊，不接受第二个门客
                if(i > 1 && unionWarUserPatrons.getGoodsId() != eItemId.UNION_WAR_ACTIVITY_SMFB_JN.getValue()){
                    continue;
                }
                Map<Integer, UserPatrons> userPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
                UserPatrons userPatrons = userPatronsMap.get(patronsId);
                UserPatronsSendTimes patronsSendTimes = getAndCheckUserPatronsSendTimes(player.getUserId(), patronsId);
                patronsSendTimes.setTimes(patronsSendTimes.getTimes() + 1);

                UnionWarUserPatronsDetail patronsDetail = new UnionWarUserPatronsDetail();
                //现装备的珍兽
                UserVehicle userVehicle = player.getModule(VehicleModule.class).getEquipVehicle(patronsId);
                if(userVehicle != null){
                    UserVehicleSendTimes vehicleSendTimes = getAndCheckUserVehicleSendTimes(player.getUserId(), userVehicle.getVehicleUid());
                    vehicleSendTimes.setTimes(vehicleSendTimes.getTimes() + 1);
                    newVehicle.put(patronsId, userVehicle.getVehicleUid());
                }

                //现装备的鱼类
                Map<Integer, FishData> fishDataMap = player.getModule(ManorModule.class).getManorFishPondModel().getFishDataMap();
                FishData fishData = FishPondMgr.getUserFishByPatrons(patronsId, fishDataMap);
                if (fishData != null) {
                    UserFishSendTimes fishSendTimes = getAndCheckUserFishSendTimes(player.getUserId(), fishData.getFishId());
                    fishSendTimes.setTimes(fishSendTimes.getTimes() + 1);
                    newFish.put(patronsId, fishData.getFishId());
                }

                //昆虫
                Map<Integer, CricketData> cricketDataMap = player.getModule(CricketModule.class).getCricketDataMap();
                CricketData cricketData = CricketMgr.getUserCricketByPatrons(patronsId, cricketDataMap);
                if (cricketData != null) {
                    UserCricketSendTimes cricketSendTimes = getAndCheckUserCricketSendTimes(player.getUserId(), cricketData.getCricketId());
                    cricketSendTimes.setTimes(cricketSendTimes.getTimes() + 1);
                    newCricket.put(patronsId, cricketData.getCricketId());
                }

                patronsDetail.setPatronsId(patronsId);
                patronsDetail.setAbility(userPatrons.getAbility().longValue());
                patronsDetail.setSkinId(userPatrons.getSkinId());
                patronsDetail.setPatronsLv(userPatrons.getLevel());
                patronsDetail.setPromotionId(userPatrons.getShowPromotionId());
                patronsDetail.setPatronsStageLv(userPatrons.getStageLv());
                patronsDetail.setSkillAddition(getAbilityTalentAddition(userPatronsMap));
                patronsDetail.setLianShengAddition(getLianShengTalentAddition(userPatrons));
                if(i > 1){
                    patronsDetail.setType(1);
                }
                newPatronsDetail.put(patronsId, patronsDetail);
                try {
                    //已派遣的不重复记录日志
                    if (!oldPatrons.contains(patronsId)) {
                        AutoLogMgr.add(new LogUnionWarActivityDispatch(player.getUserId(), activityInfo.getActivityId(), unionUid, UnionConfigMgr.getUnionLv(unionInfo.getExperience()),
                                position, phase, session, patronsId, userPatrons.getAbility().longValue(), i > 1));
                    }
                }catch (Exception e){
                    logger.error(e.getMessage(), e);
                }
                i++;
            }
            //重置旧出战次数
            for(int patronsId : oldPatrons) {
                UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(patronsId);
                if(userPatrons != null) {
                    UserPatronsSendTimes patronsSendTimes = getUserPatronsSend(player.getUserId(), patronsId);
                    if(patronsSendTimes != null && patronsSendTimes.getTimes() > 0) {
                        patronsSendTimes.setTimes(patronsSendTimes.getTimes() - 1);
                    }
                }
            }
            //重置旧珍兽出战次数
            for(String vehicleUid : oldVehicleList){
                UserVehicle oldUserVehicle = player.getModule(VehicleModule.class).getUserVehicle(vehicleUid);
                if(oldUserVehicle != null){
                    UserVehicleSendTimes vehicleSendTimes = getUserVehicleSend(player.getUserId(), oldUserVehicle.getVehicleUid());
                    if(vehicleSendTimes != null && vehicleSendTimes.getTimes() > 0) {
                        vehicleSendTimes.setTimes(vehicleSendTimes.getTimes() - 1);
                    }
                }
            }

            //重置旧鱼类出战次数
            for(Integer fishId : oldFishList){
                FishData oldFishData = player.getModule(ManorModule.class).getManorFishPondModel().getFishDataMap().get(fishId);
                if(oldFishData != null){
                    UserFishSendTimes fishSendTimes = getUserFishSend(player.getUserId(), oldFishData.getFishId());
                    if(fishSendTimes != null && fishSendTimes.getTimes() > 0) {
                        fishSendTimes.setTimes(fishSendTimes.getTimes() - 1);
                    }
                }
            }
            //重置旧昆虫类出战次数
            for(Integer cricketId : oldCricketList){
                CricketData cricketData = player.getModule(CricketModule.class).getCricketDataMap().get(cricketId);
                if(cricketData != null){
                    UserCricketSendTimes cricketSendTimes = getUserCricketSend(player.getUserId(), cricketData.getCricketId());
                    if(cricketSendTimes != null && cricketSendTimes.getTimes() > 0) {
                        cricketSendTimes.setTimes(cricketSendTimes.getTimes() - 1);
                    }
                }
            }
        }
        synchronized (detail){
            unionWarUserPatrons.setPosition(position);
            for(UnionWarUserPatronsDetail patronsDetail : newPatronsDetail.values()){
                patronsDetail.setAbility2(UnionPhaseWarMgr.unionPositionAndSkillEffectPatronsData(patronsDetail.getAbility(), unionWarUserPatrons.getPosition(), activityInfo, patronsDetail.getSkillAddition()));
            }
            unionWarUserPatrons.setPatrons(newPatronsDetail);
            unionWarUserPatrons.setVehicleUidList(newVehicle);
            unionWarUserPatrons.setFishIdList(newFish);
            unionWarUserPatrons.setCricketIdList(newCricket);
            detail.putPatrons(player.getUserId(), unionWarUserPatrons);
            //玩家信息
            detail.putUserBaseInfo(player.getUserId(), UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId()));
            detail.setLastUpdateTime(System.currentTimeMillis());
        }

        syncUnionWarPrepareData();

        //返回消息
        UnionWarActivityServerProto.UserDispatchRespMsg.Builder respMsg = UnionWarActivityServerProto.UserDispatchRespMsg.newBuilder();
        UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(detail.getUnionUid());
        respMsg.setLineupInfo(UnionWarActivityPb.parseSessionLineupTempList(detail, true, getCanDispatchMemberList(detail.getUnionUid()).size(), detail.getEnemyUnionInfo(), unionBaseInfo));
        respMsg.setRet(0);
        respMsg.setPhase(phase);
        respMsg.setSession(session);
        player.sendPacket(Protocol.U_UNION_WAR_USER_PATRONS_DISPATCH, respMsg);
        player.sendPacket(Protocol.U_UNION_WAR_USER_DATA_INFO_SYNC, player.getModule(UnionWarActivityModule.class).buildUserDataInfoTempBuilder(activityInfo.getActivityId()));
        return 0;
    }

    /**
     * 获取并初始化门客出战次数
     * @param userId
     * @param patronsId
     * @return
     */
    public UserPatronsSendTimes getAndCheckUserPatronsSendTimes(long userId, int patronsId) {
        if(!getUserPatronsSendMap().containsKey(userId)){
            getUserPatronsSendMap().put(userId, new HashMap<>());
        }
        UserPatronsSendTimes patronsSendTimes = getUserPatronsSendMap().get(userId).get(patronsId);
        if(patronsSendTimes == null){
            patronsSendTimes = new UserPatronsSendTimes();
            patronsSendTimes.setPatronsId(patronsId);
            patronsSendTimes.setActivityId(activityInfo.getActivityId());
            patronsSendTimes.setUserId(userId);
            patronsSendTimes.setInsertOption();
            getUserPatronsSendMap().get(userId).put(patronsId, patronsSendTimes);
        }
        return patronsSendTimes;
    }

    /**
     * 获取并初始化珍兽出战次数
     * @param userId
     * @param vehicleId
     * @return
     */
    public UserVehicleSendTimes getAndCheckUserVehicleSendTimes(long userId, String vehicleId) {
        if(!getUserVehicleSendMap().containsKey(userId)){
            getUserVehicleSendMap().put(userId, new ConcurrentHashMap<>());
        }
        UserVehicleSendTimes vehicleSendTimes = getUserVehicleSendMap().get(userId).get(vehicleId);
        if(vehicleSendTimes == null){
            vehicleSendTimes = new UserVehicleSendTimes();
            vehicleSendTimes.setVehicleUid(vehicleId);
            vehicleSendTimes.setActivityId(activityInfo.getActivityId());
            vehicleSendTimes.setUserId(userId);
            vehicleSendTimes.setInsertOption();
            getUserVehicleSendMap().get(userId).put(vehicleId, vehicleSendTimes);
        }
        return vehicleSendTimes;
    }

    /**
     * 获取并初始化珍兽出战次数
     * @param userId
     * @param fishId
     * @return
     */
    public UserFishSendTimes getAndCheckUserFishSendTimes(long userId, int fishId) {
        if(!getUserFishSendMap().containsKey(userId)){
            getUserFishSendMap().put(userId, new ConcurrentHashMap<>());
        }
        UserFishSendTimes fishSendTimes = getUserFishSendMap().get(userId).get(fishId);
        if(fishSendTimes == null){
            fishSendTimes = new UserFishSendTimes();
            fishSendTimes.setFishId(fishId);
            fishSendTimes.setActivityId(activityInfo.getActivityId());
            fishSendTimes.setUserId(userId);
            fishSendTimes.setInsertOption();
            getUserFishSendMap().get(userId).put(fishId, fishSendTimes);
        }
        return fishSendTimes;
    }

    public UserCricketSendTimes getAndCheckUserCricketSendTimes(long userId, int cricketId) {
        if(!getUserCricketSendMap().containsKey(userId)){
            getUserCricketSendMap().put(userId, new ConcurrentHashMap<>());
        }
        UserCricketSendTimes cricketSendTimes = getUserCricketSendMap().get(userId).get(cricketId);
        if(cricketSendTimes == null){
            cricketSendTimes = new UserCricketSendTimes();
            cricketSendTimes.setCricketId(cricketId);
            cricketSendTimes.setActivityId(activityInfo.getActivityId());
            cricketSendTimes.setUserId(userId);
            cricketSendTimes.setInsertOption();
            getUserCricketSendMap().get(userId).put(cricketId, cricketSendTimes);
        }
        return cricketSendTimes;
    }

    /**
     * 募捐银两
     * @param player
     * @param unionUid
     * @param phase
     * @param session
     * @param silverNum
     * @return
     */
    public int donateSilver(GamePlayer player, String unionUid, int phase, int session, BigInteger silverNum) {
        //是否参与活动
        boolean join = isJoinCurrentTimeInfo(unionUid, null);
        if (!join) {
            return GameErrorCode.E_UNION_WAR_ACTIVITY_NO_JOIN_SESSION;
        }
        int ret = checkTimeInfoInPrepareTime(phase, session);
        if (ret != 0) {
            return ret;
        }

        Object locker = getUnionLocker(unionUid);
        UnionWarDispatchDetail detail;
        //synchronized (locker) {
        //    detail = checkAndGetUnionWarDispatchDetails(unionUid, phase, session);
        //}
        detail = getUnionWarDispatchDetailList(unionUid, phase, session);
        if(detail == null){
            return GameErrorCode.E_UNION_WAR_ACTIVITY_NO_JOIN_SESSION;
        }
        UnionWarUserSilver userSilver;
        synchronized (getUserLocker(player.getUserId())) {
            Property silverConsume = new Property(GameConfig.GAME_MONEY_SILVER, silverNum);
            //银两是否足够
            if (!player.getModule(CurrencyModule.class).removeCurrency(silverConsume, eLogMoneyType.Activity, eLogMoneyType.UnionWarActivitySilverDonate)) {
                return GameErrorCode.E_BAG_SILVER_NO_ENOUGH;
            }
            userSilver = detail.getSilverMap().get(player.getUserId());
            if (userSilver == null) {
                userSilver = new UnionWarUserSilver();
                userSilver.setUserId(player.getUserId());
            }
            userSilver.setSilver(userSilver.getSilver().add(silverNum));
            userSilver.setNickName(player.getUserInfo().getNickName());
            userSilver.setPosition(GameUnionActivityGroupMgr.getUnionPosition(activityInfo.getActivityId(), player.getUserId()));
        }
        UserBaseInfo userBaseInfo = UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId());
        synchronized (detail){
            detail.putSilver(player.getUserId(), userSilver);
            detail.putUserBaseInfo(player.getUserId(), userBaseInfo);
            detail.setLastUpdateTime(System.currentTimeMillis());
        }
        //推给玩家
        UnionWarActivityServerProto.UserDonateSilverRespMsg.Builder respMsg = UnionWarActivityServerProto.UserDonateSilverRespMsg.newBuilder();
        UnionBaseInfo unionInfo = CrossUnionMgr.parseUnionBaseInfo(detail.getUnionUid());
        respMsg.setLineupInfo(UnionWarActivityPb.parseSessionLineupTempList(detail, true, getCanDispatchMemberList(detail.getUnionUid()).size(), detail.getEnemyUnionInfo(), unionInfo));
        respMsg.setRet(0);
        respMsg.setPhase(phase);
        respMsg.setSession(session);
        player.sendPacket(Protocol.U_UNION_WAR_USER_SILVER_DISPATCH, respMsg);

        //推送跨服
        CrossUnionWarProto.CrossUnionWarDonateSilverReqMsg.Builder crossSilverReqMsg = CrossUnionWarProto.CrossUnionWarDonateSilverReqMsg.newBuilder();
        crossSilverReqMsg.setActivityId(activityInfo.getActivityId());
        crossSilverReqMsg.setPhase(phase);
        crossSilverReqMsg.setSession(session);
        crossSilverReqMsg.setUnionUid(detail.getUnionUid());
        crossSilverReqMsg.setDonateSilver(String.valueOf(userSilver.getSilver()));
        crossSilverReqMsg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        //player.sendChannelPacket(Protocol.C_CROSS_UNION_DONATE_SILVER, crossSilverReqMsg);
        player.sendUnionActivityGroupPacket(Protocol.C_CROSS_UNION_DONATE_SILVER, crossSilverReqMsg, activityInfo.getActivityId());
        return 0;
    }

    /**
     * 获取商会的积分、排名（后面改为从排行榜获取）
     * @param player
     * @param unionUid
     * @param phase
     * @return
     */
    public int getUnionScoreRank(GamePlayer player, String unionUid, int phase, int groupId) {
        //是否参与活动
        boolean join = isJoin(unionUid);
        if(!join){
            return GameErrorCode.E_ACTIVITY_NO_JOIN;
        }
        UnionWarActivityServerProto.UnionScoreAndRankRespMsg.Builder respMsg = UnionWarActivityServerProto.UnionScoreAndRankRespMsg.newBuilder();
        // 积分、排行
        UnionWarUnionJoin unionName = getUnionWarNameList(unionUid);
        if(unionName != null){
            if(phase == 1){
                respMsg.setRank(unionName.getPhaseOneRank());
                respMsg.setScore(unionName.getPhaseOneScore());
                if(unionName.getPhaseOneRank() <= 0){
                    //从排行榜拿数据
                    CrossActivityProto.UnionWarRankMsgMsg.Builder unionWarRankListMsg = CrossDataMgr.getUnionWarRankListMsg(activityInfo.getActivityId(), 1, groupId);
                    if(unionWarRankListMsg.getRankList() != null) {
                        int i = 1;
                        for (UnionActivityRankProto.UnionActivityRankTempMsg msg : unionWarRankListMsg.getRankList().getRankListList()) {
                            if(msg.getUnionUid().equals(unionUid)){
                                respMsg.setRank(i);
                                break;
                            }
                            i++;
                        }
                    }
                }
            }else if(phase == 2){
                respMsg.setRank(unionName.getPhaseTwoRank());
                respMsg.setScore(unionName.getPhaseTwoScore());
            }
        }
        respMsg.setActivityId(activityInfo.getActivityId());
        respMsg.setRet(0);
        respMsg.setPhase(phase);
        player.sendPacket(Protocol.U_UNION_WAR_UNION_SCORE_RANK, respMsg);
        return 0;
    }

    /**
     * 领取战斗结果奖励
     * @param timeInfo
     * @param win
     * @return
     */
    public Property getBattleReward(UnionQunyingTimeInfo timeInfo, boolean win, boolean isMaster) {
        Property property = new Property();
        String rewardStr;
        if(isMaster){
            rewardStr = timeInfo.getRewardsPresident();
        }else{
            rewardStr = timeInfo.getRewardsMember();
        }
        List<String> rewardStrList = StringUtils.stringToStringList(rewardStr, "\\|");
        if(rewardStrList.size() != 2){
            return property;
        }
        if(win){
            property = PropertyHelper.parseStringToProperty(rewardStrList.get(0));
        }else {
            property = PropertyHelper.parseStringToProperty(rewardStrList.get(1));
        }
        return  property;
    }

    public String isCanGetRewardMember(String unionUid, int phase, long userId) {
        if (canGetRankRewardMemberMap.containsKey(unionUid)) {
            if (canGetRankRewardMemberMap.get(unionUid).containsKey(phase)) {
                if (canGetRankRewardMemberMap.get(unionUid).get(phase).containsKey(userId)) {
                    return unionUid;
                }
            }
        }
        for (Map<Integer, Map<Long, UnionWarRankMember>> mapMap : canGetRankRewardMemberMap.values()) {
            if (mapMap.containsKey(phase)) {
                for (UnionWarRankMember member : mapMap.get(phase).values()) {
                    if (member.getUserId() == userId) {
                        return member.getUnionUid();
                    }
                }
            }
        }
        return "";
    }

    /**
     * 阶段结束时确定商会成员
     * @param unionUid  商会Uid
     * @param phase     阶段
     */
    public void syncCanGetRankRewardMemberMap(String unionUid, int phase) {
        synchronized (canGetRankRewardMemberMap) {
            if (!canGetRankRewardMemberMap.containsKey(unionUid)) {
                canGetRankRewardMemberMap.put(unionUid, new ConcurrentHashMap<>());
            }
            if (!canGetRankRewardMemberMap.get(unionUid).containsKey(phase)) {
                Map<Long, UnionWarRankMember> unionWarRankMemberMap = new ConcurrentHashMap<>();

                UnionActivityGroupUnion groupUnion = GameUnionActivityGroupMgr.getUnionData(activityInfo.getActivityId(), unionUid);
                if(groupUnion == null){
                    return;
                }
                for (Map.Entry<Long, UnionActivityGroupUser> entry : groupUnion.getUserMap().entrySet()) {
                    UnionWarRankMember unionWarRankMember = new UnionWarRankMember();
                    unionWarRankMember.setActivityId(activityInfo.getActivityId());
                    unionWarRankMember.setUnionUid(unionUid);
                    unionWarRankMember.setPhase(phase);
                    unionWarRankMember.setUserId(entry.getKey());
                    unionWarRankMember.setPositionId(entry.getValue().getPosition());
                    unionWarRankMember.setInsertOption();
                    unionWarRankMemberMap.put(unionWarRankMember.getUserId(), unionWarRankMember);
                }
                canGetRankRewardMemberMap.get(unionUid).put(phase, unionWarRankMemberMap);
            }
        }
    }

    public UnionWarRankMember getUnionWarRankMember(String unionUid, int phase, long userId) {
        if (canGetRankRewardMemberMap.containsKey(unionUid)) {
            if (canGetRankRewardMemberMap.get(unionUid).containsKey(phase)) {
                return canGetRankRewardMemberMap.get(unionUid).get(phase).get(userId);
            }
        }
        return null;
    }

    public UnionWarUnionMember getUnionWarUnionMember(String unionUid, int phase, int session){
        if (unionMemberMap.containsKey(unionUid)){
            if (unionMemberMap.get(unionUid).containsKey(phase)){
                return unionMemberMap.get(unionUid).get(phase).get(session);
            }
        }
        return null;
    }

    /**
     * 竞猜商会数据同步
     *
     * @param syncMsg 同步数据
     */
    public void guessUnionInfoSync(UnionWarActivityServerProto.UnionWarGuessSyncMsg syncMsg) {
        synchronized (guessUnionInfoMap) {
            if (!guessUnionInfoMap.containsKey(syncMsg.getStage())) {
                guessUnionInfoMap.put(syncMsg.getStage(), new ConcurrentHashMap<>());
            }
            for (UnionWarActivityServerProto.UnionWarGuessTemp unionWarGuessTemp : syncMsg.getUnionWarGuessList()) {
                if (!guessUnionInfoMap.get(syncMsg.getStage()).containsKey(unionWarGuessTemp.getUnionBaseTemp().getServerId())) {
                    guessUnionInfoMap.get(syncMsg.getStage()).put(unionWarGuessTemp.getUnionBaseTemp().getServerId(), new ConcurrentHashMap<>());
                }
                GuessUnionInfo guessUnionInfo = new GuessUnionInfo();
                guessUnionInfo.setActivityId(activityInfo.getActivityId());
                guessUnionInfo.setPhase(syncMsg.getStage());
                guessUnionInfo.setGroupId(unionWarGuessTemp.getGroupId());
                guessUnionInfo.setUnionUid(unionWarGuessTemp.getUnionUid());
                guessUnionInfo.setUnionBaseInfo(CrossRankPb.parseUnionBaseInfo(unionWarGuessTemp.getUnionBaseTemp()));
                guessUnionInfo.setGuessPopularity(unionWarGuessTemp.getPopularity());
                guessUnionInfoMap.get(syncMsg.getStage()).get(unionWarGuessTemp.getUnionBaseTemp().getServerId()).put(unionWarGuessTemp.getUnionUid(), guessUnionInfo);
            }
        }
    }

    /**
     * 同步各档位达成人数数据
     * @param msg   数据
     */
    public void conditionAchieveInfoSync(UnionWarActivityServerProto.UnionWarConditionAchieveMsg msg) {
        synchronized (conditionAchieveInfoMap) {
            for (UnionWarActivityServerProto.UnionWarConditionAchieveTemp achieveTemp : msg.getUnionWarConditionAchieveList()) {
                ConditionAchieveInfo conditionAchieveInfo = new ConditionAchieveInfo();
                conditionAchieveInfo.setActivityId(activityInfo.getActivityId());
                conditionAchieveInfo.setConditionId(achieveTemp.getConditionId());
                conditionAchieveInfo.setAchieveCount(achieveTemp.getAchieveCount());
                conditionAchieveInfo.setGroupId(achieveTemp.getGroupId());
                conditionAchieveInfo.setUserList(new ArrayList<>());
                for (PlayerProto.PlayerBaseTempMsg playerBaseTempMsg : achieveTemp.getPlayerBaseInfoList()) {
                    conditionAchieveInfo.getUserList().add(PlayerBasePb.parseBaseUserInfo(playerBaseTempMsg));
                }
                if(!conditionAchieveInfoMap.containsKey(achieveTemp.getGroupId())){
                    conditionAchieveInfoMap.put(achieveTemp.getGroupId(), new ConcurrentHashMap<>());
                }
                conditionAchieveInfoMap.get(achieveTemp.getGroupId()).put(achieveTemp.getConditionId(), conditionAchieveInfo);
            }
        }
    }

    public Map<Integer, Map<Integer, ConditionAchieveInfo>> getConditionAchieveInfoMap() {
        return conditionAchieveInfoMap;
    }

    public Map<Long, Map<String, GuessUnionInfo>> getGuessUnionInfo(int phase) {
        return guessUnionInfoMap.get(phase);
    }

    /**
     * 获取竞猜列表
     * @param player
     */
    public void syncGuessListMsg(GamePlayer player) {
        UnionWarActivityServerProto.GetUnionWarGuessListRespMsg.Builder respMsg = UnionWarActivityServerProto.GetUnionWarGuessListRespMsg.newBuilder();
        //阶段
        for (int stage = 1; stage <= 2; stage++) {
            UnionWarActivityServerProto.UnionWarGuessListTemp.Builder listTemp = UnionWarActivityServerProto.UnionWarGuessListTemp.newBuilder();
            listTemp.setStage(stage);

            //先用我的竞猜数据，决定显示哪组数据（热度及排行）
            int myGroupId = GameUnionActivityGroupMgr.getViewDataGroupId(this.activityInfo.getActivityId(), player.getUserId());

            //我的竞猜数据
            UserUnionWarGuessData guessData = player.getModule(UnionWarActivityModule.class).getGuessData(activityInfo.getActivityId(), stage);
            if (guessData != null) {
                for (BaseUnionGuessInfo guessUnionBaseInfo : guessData.getGuessUnionBaseInfos()) {
                    int tempGroupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), guessUnionBaseInfo.getUnionUid());
                    if(tempGroupId != myGroupId){
                        logger.info("activityId {} userId {} myGroupId {} guessDataId {}", activityInfo.getActivityId(), player.getUserId(), myGroupId, tempGroupId);
                        myGroupId = tempGroupId;
                    }
                    UnionWarActivityServerProto.UnionWarGuessDataTemp.Builder userGuessData = UnionWarActivityServerProto.UnionWarGuessDataTemp.newBuilder();
                    userGuessData.setServerId(guessUnionBaseInfo.getServerId());
                    userGuessData.setUnionUid(guessUnionBaseInfo.getUnionUid());
                    listTemp.addUserGuessUnion(userGuessData);
                }
            }

            //竞猜热度
            List<String> unionList = getGroupUnionList(this.activityInfo.getActivityId(), myGroupId);
            for (Map.Entry<Integer, Map<Long, Map<String, GuessUnionInfo>>> entry : guessUnionInfoMap.entrySet()) {
                //过滤阶段
                if(entry.getKey() != stage){
                    continue;
                }
                for (Map<String, GuessUnionInfo> map : entry.getValue().values()) {
                    for (GuessUnionInfo info : map.values()) {
                        if (unionList.size() > 0 && !unionList.contains(info.getUnionUid())) {
                            continue;
                        }
                        if (info.getGroupId() != myGroupId) {
                            continue;
                        }
                        listTemp.addUnionWarGuess(UnionWarActivityPb.parseUnionWarGuessTemp(info));
                    }
                }
            }

            if (checkInGetRewardTime(stage)) {
                CrossActivityProto.UnionWarRankMsgMsg.Builder rankListMsg = CrossDataMgr.getUnionWarRankListMsg(activityInfo.getActivityId(), stage, myGroupId);
                List<UnionActivityRankProto.UnionActivityRankTempMsg> rankList = rankListMsg.getRankList().getRankListList();
                int n = 8;
                ActivityInfo activityInfo = UnionWarActivityMgr.getOpenActivityInfo(getActivityInfo().getActivityId());
                try {
                    n = Integer.parseInt(activityInfo.getParam4().split(";")[2]);
                } catch (Exception e) {
                    UnionPhaseWarMgr.getLogger().error(e.getMessage(), e);
                }
                if(stage == 2){
                    n = 8;
                }
                if(rankList.size() < n){
                    n = rankList.size();
                }
                for (int i = 0; i < n; i++) {
                    UnionActivityRankProto.UnionActivityRankTempMsg rank = rankList.get(i);
                    UnionWarActivityServerProto.UnionWarGuessDataTemp.Builder unionRank = UnionWarActivityServerProto.UnionWarGuessDataTemp.newBuilder();
                    unionRank.setServerId(rank.getUnionBaseData().getServerId());
                    unionRank.setUnionUid(rank.getUnionUid());
                    unionRank.setValue(rank.getValue());
                    listTemp.addUnionRank(unionRank);
                }
            }
            if (stage == 2) {
                List<UnionWarActivityServerProto.UnionWarGuessTemp> unionWarGuessList = new ArrayList<>(listTemp.getUnionWarGuessList());
                sortGuessList(unionWarGuessList, myGroupId);
                listTemp.clearUnionWarGuess();
                listTemp.addAllUnionWarGuess(unionWarGuessList);
            }
            respMsg.addUnionWarGuessList(listTemp);
        }
        player.sendPacket(ClientProtocol.U_UNION_WAR_ACTIVITY_GET_GUESS_LIST, respMsg);
    }

    public void sortGuessList(List<UnionWarActivityServerProto.UnionWarGuessTemp> unionWarGuessList, int groupId) {
        CrossActivityProto.UnionWarRankMsgMsg.Builder rankListMsg = CrossDataMgr.getUnionWarRankListMsg(activityInfo.getActivityId(), 1, groupId);
        List<UnionActivityRankProto.UnionActivityRankTempMsg> rankList = rankListMsg.getRankList().getRankListList();
        unionWarGuessList.sort((o1, o2) -> {
            int o1Value = 0;
            int o2Value = 0;
            for (UnionActivityRankProto.UnionActivityRankTempMsg union : rankList) {
                if (union.getUnionBaseData().getServerId() == o1.getUnionBaseTemp().getServerId() && union.getUnionUid().equals(o1.getUnionUid())) {
                    o1Value = Integer.parseInt(union.getValue());
                    continue;
                }
                if (union.getUnionBaseData().getServerId() == o2.getUnionBaseTemp().getServerId() && union.getUnionUid().equals(o2.getUnionUid())) {
                    o2Value = Integer.parseInt(union.getValue());
                    continue;
                }
                if (o1Value > 0 && o2Value > 0) {
                    break;
                }
            }
            return o2Value - o1Value;
        });
    }

    /**
     * 返回门客、珍兽的出战次数
     * @param unionWarUserPatrons   撤回的门客、珍兽信息
     */
    public void giveBackPatronsVehicleWarTimes(UnionWarUserPatrons unionWarUserPatrons){
        long userId = unionWarUserPatrons.getUserId();
        synchronized (getUserLocker(userId)) {
            if (getUserPatronsSendMap().containsKey(userId)) {
                Map<Integer, UserPatronsSendTimes> userPatronsSendTimesMap = getUserPatronsSendMap().get(userId);
                for(UnionWarUserPatronsDetail patronsDetail : unionWarUserPatrons.getPatrons().values()){
                    UserPatronsSendTimes patronsSendTimes = userPatronsSendTimesMap.get(patronsDetail.getPatronsId());
                    if(patronsSendTimes != null && patronsSendTimes.getTimes() > 0){
                        patronsSendTimes.setTimes(patronsSendTimes.getTimes() - 1);
                    }
                }
            }
            if (getUserVehicleSendMap().containsKey(userId)) {
                Map<String, UserVehicleSendTimes> userVehicleSendTimesMap = getUserVehicleSendMap().get(userId);
                for(String vehicleUid : unionWarUserPatrons.getVehicleUidList().values()){
                    UserVehicleSendTimes vehicleSendTimes = userVehicleSendTimesMap.get(vehicleUid);
                    if(vehicleSendTimes != null && vehicleSendTimes.getTimes() > 0){
                        vehicleSendTimes.setTimes(vehicleSendTimes.getTimes() - 1);
                    }
                }
            }
            if (getUserFishSendMap().containsKey(userId)) {
                Map<Integer, UserFishSendTimes> userFishSendTimesMap = getUserFishSendMap().get(userId);
                for(Integer fishId : unionWarUserPatrons.getFishIdList().values()){
                    UserFishSendTimes userFishSendTimes = userFishSendTimesMap.get(fishId);
                    if(userFishSendTimes != null && userFishSendTimes.getTimes() > 0){
                        userFishSendTimes.setTimes(userFishSendTimes.getTimes() - 1);
                    }
                }
            }
        }
    }

    /**
     * 请求决赛淘汰信息 v2.6
     */
    public void backUserGoodsInFinals() {
        CurrentTimeInfo currentTimeInfo = getCurrentTimeInfo();
        UnionQunyingTimeInfo timeInfo = currentTimeInfo.getTimeInfo();
        //领奖期且决赛第二轮以后
        if(currentTimeInfo.getPeriodType() == eTimeInfoPeriodType.ReceiveTime ||
                (timeInfo != null && timeInfo.getType() == 2 && timeInfo.getSession() > 1)){


            List<Integer> groupIdList = UnionWar.getGroupListByServerId(getActivityInfo().getActivityId(), GameServer.getInstance().getServerId());
            for (int groupId : groupIdList) {
                //上跨服拿决赛对阵
                CrossUnionWarProto.CrossGetEliminationInfoReqMsg.Builder reqMsg = CrossUnionWarProto.CrossGetEliminationInfoReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_UNION_WAR_REQ_FINALS_RESULT, reqMsg, 0, activityInfo.getActivityId(), groupId);
            }
        }
    }

    /**
     * 决赛备战锦囊归还 v2.6
     * @param respMsg
     */
    public void backUserGoodsInFinalsFromCross(CrossUnionWarProto.CrossGetEliminationInfoRespMsg respMsg) {
        int allSession = getAllSession(2);
        for(CrossUnionWarProto.CrossUnionEliminationSessionTemp sessionTemp : respMsg.getSessionList()){
            Map<Long, Property> userGoodsMap = new HashMap<>();
            for(int s = sessionTemp.getSession() + 1; s <= allSession; s++) {
                UnionWarDispatchDetail detail = getUnionWarDispatchDetailList(sessionTemp.getUnionUid(), 2, s);
                if(detail != null && detail.getWinMark() == eUnionWarWinMark.Default.getValue()){
                    synchronized (detail){
                        boolean change = false;
                        for(Map.Entry<Long, UnionWarUserPatrons> entry : detail.getPatronsMap().entrySet()){
                            long userId = entry.getKey();
                            UnionWarUserPatrons userPatrons = entry.getValue();
                            if(userPatrons.isBackGoods() || userPatrons.getGoodsId() == 0){
                                continue;
                            }
                            if(userPatrons.getServerId() != GameServer.getInstance().getServerId()){
                                //UnionPhaseWarMgr.getLogger().error("UnionWar backUserGoods user: {} no same server", userPatrons.getUserId());
                                continue;
                            }
                            if(!userGoodsMap.containsKey(userId)){
                                userGoodsMap.put(userId, new Property());
                            }
                            userGoodsMap.get(userId).addProperty(userPatrons.getGoodsId(), BigInteger.ONE);
                            userPatrons.setBackGoods(true);
                            change = true;
                        }
                        if(change){
                            detail.setUpdateOption();
                        }
                    }
                }
            }
            for(Map.Entry<Long, Property> entry : userGoodsMap.entrySet()){
                long userId = entry.getKey();
                UserInfo userInfo = UserMgr.getUserInfo(userId);
                if(userInfo == null){
                    //UnionPhaseWarMgr.getLogger().error("UnionWar backUserGoods user: {} no same server", userId);
                    continue;
                }
                String title = MultipleLanguageMgr.getContent(MailManager.UNION_WAR_ACTIVITY_JIN_NANG_BACK_TITLE, userInfo.getLanguage());
                String content = MultipleLanguageMgr.getContent(MailManager.UNION_WAR_ACTIVITY_JIN_NANG_BACK_CONTENT, userInfo.getLanguage());
                MailManager.sendMail(userId, eMailType.SYSTEM.getValue(), PropertyHelper.parsePropertyToString(entry.getValue()), content, title);
            }
        }
    }

    /**
     * 获取门客赚钱天赋加成
     */
    public static int getAbilityTalentAddition(Map<Integer, UserPatrons> userPatronsMap) {
        int talentAddition = 0;
        for (UserPatrons userPatrons : userPatronsMap.values()) {
            for (UserPatronsSkill patronsSkill : userPatrons.getSkillList()) {
                if (patronsSkill.getType() != ePatronsSkillType.Talent.getValue()) {
                    continue;
                }
                SkillInfo skillInfo = SkillMgr.getSkillInfo(patronsSkill.getSkillId());
                if (skillInfo.getType() == eSkillType.CrossUnionWarAbilityAddition.getValue()) {
                    talentAddition += SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
                }
            }
        }
        return talentAddition;
    }

    /**
     * 获取连胜次数上限加成
     */
    public static int getLianShengTalentAddition(UserPatrons userPatrons) {
        int talentAddition = 0;
        for (UserPatronsSkill patronsSkill : userPatrons.getSkillList()) {
            if (patronsSkill.getType() != ePatronsSkillType.Talent.getValue()) {
                continue;
            }
            SkillInfo skillInfo = SkillMgr.getSkillInfo(patronsSkill.getSkillId());
            if (skillInfo.getType() == eSkillType.CrossUnionWarLianShengTimesAddition.getValue()) {
                talentAddition += SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
            }
        }
        return talentAddition;
    }

    public Map<String, Map<Integer, Map<Integer, UnionWarDispatchDetail>>> getUnionDispatchDetailMap() {
        return unionDispatchDetailMap;
    }

    //分组数据过滤

    /**
     * 玩家的商会
     */
    public static String getUserUnionUid(int activityId, UserInfo userInfo){
        return GameUnionActivityGroupMgr.getUnionUid(activityId, userInfo.getUserId());
    }

    public static List<String> getGroupUnionList(int activityId, long userId){
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, userId);
        return getGroupUnionList(activityId, groupId);
    }

    public static List<String> getGroupUnionList(int activityId, int groupId){
        UnionActivityGroup group = GameUnionActivityGroupMgr.getGroupData(activityId, groupId);
        if(group != null){
            return new ArrayList<>(group.getUnionDataMap().keySet());
        }
        return new ArrayList<>();
    }

    public static List<Integer> getGroupListByServerId(int activityId, long serverId){
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityId);
        if(groupMap == null){
            return new ArrayList<>();
        }
        List<Integer> groupIdList = new ArrayList<>();
        for (Map.Entry<Integer, UnionActivityGroup> groupEntry : groupMap.entrySet()) {
            if(groupEntry.getValue().getServerSet().contains(serverId)){
                groupIdList.add(groupEntry.getValue().getGroupId());
            }
        }
        return groupIdList;
    }

    public static List<String> getGroupUnionUidList(int activityId, int groupId){
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityId);
        if(groupMap == null || !groupMap.containsKey(groupId)){
            return new ArrayList<>();
        }
        UnionActivityGroup group = groupMap.get(groupId);
        List<String> unionList = new ArrayList<>(group.getUnionDataMap().keySet());
        return unionList;
    }
}
